离子角 单击按钮后更新$scope变量

Ionic angular Update $scope variable after click a button

本文关键字:更新 scope 变量 按钮 单击      更新时间:2023-09-26

我想在单击保存按钮的那一刻更新我的$scope变量,基本上我正在尝试更新配置文件名称,所以我需要当我按下保存按钮时,这个新名称立即显示在图像配置文件旁边的导航栏中,我尝试了以下方法...但对我不起作用,我确实使用了$apply:

控制器.js

.controller('ProfileCtrl', function($ionicPlatform, $cordovaMedia, $scope, Words, Utilities, $timeout) {
   
   $scope.save = function(){
var content = toTitleCase($scope.editWordRow.title);
       //$scope.profilename = '';
        
       $timeout(function () {
         $scope.$apply(function () {
            $scope.profilename = content;
            console.log('profile name tiene esto, deberia mostrarse al salir de guardar: ' + $scope.profilename);
         });
       }, 2000);
};
// the follow $scope function is called when the controller starts
$scope.getProfileRow = function() {
    Words.getProfileSimple().then(function(single){
      if (single === null || single === undefined) {
      $scope.editWordRow = {
          title: null,
          congrats_path: null,
          name_sound_path: null,
          profile_image_path: null
      };  
      
     
      }
      else 
      {
      $scope.editWordRow = single;
      $scope.profilename = single.title;
      }
    
          
    });
      
  };
});

菜单.html

 <ion-nav-buttons side="left">
        <button class="button button-icon button-clear ion-navicon" menu-toggle="left"></button>
        
        <div style="margin: 0 auto; width:30px" ><img src="img/iconos/logo.png" width="30px" height="30px"></div>
        <div ng-controller="ProfileCtrl">
            <h4 style="color:#fff !important; margin: 5px !important;" >{{profilename}}</h4>
        </div>
 </ion-nav-buttons>

调用 save() 函数的视图为:

inicio2.html

 <ion-nav-buttons side="right">
        
        
        <button class="button button-icon button-clear ion-ios-checkmark-outline" ng-click="save()">&nbsp;</button>
    </ion-nav-buttons>

如果我在另一个视图中调用 save() 函数有问题?

谢谢,问候我将不胜感激任何帮助!

对于典型的应用程序,导航栏、页脚在所有视图中共享,如果需要共享页眉、页脚中的范围值并使它们在应用中相同,则可以使用 $rootScope.profilename 分配它们。这样,每当您更新$rootScope.profilename 时,它都会反映在整个应用程序中。

如果要

更新不受当前控制器控制的视图中的值,可以通过两种方式执行此操作:

  1. 触发事件并在实际控制菜单的正确控制器上捕获它。
  2. 使用作为两个控制器的依赖项的服务,并将变量的值存储在该服务中。

编辑:

如果变量"profileName"附加到 2 路数据绑定的范围,然后在用户输入时更改,您可以执行以下操作:

$scope.$watch('profileName', function(changedProfileName) {
  $scope.$emit('profileName:changed', changedProfileName);
});

然后,在导航栏控制器中,可以捕获事件:

$rootScope.$on('profileName:changed', function(e, newProfileName) {
  $scope.profileNameToShow = newProfileName;
});