Angular $ scope变量未在控制器中更新

时间:2016-10-08 12:01:24

标签: javascript angularjs

我的变量没有在控制器中更新,我不明白为什么。

在视图中我有这段代码

<div ng-if="state_1">
    <input ng-model='amount'> {{amount}} <!-- this binds perfectly -->
    <button ng-click='submitForm()'>Submit</button>
</div>
<div ng-if="state_2">
    <input ng-model='txcode'> {{txcode}} <!-- this binds perfectly -->
    <button ng-click='submitCode()'>Submit</button>
</div>

在控制器中:

angular.module('myapp')
   .controller('RecCtrl', function($scope, $state, $rootScope, $http) {
      $scope.submitForm = function(){
         console.log($scope.amount);    //returns undefined 
      }
   })

I followed this answer and worked around it by passing the amount into submitForm() from the view.但现在我需要使用$rootScope中的值,但没有任何显示。除了$scope.submitForm()之外,此控制器中没有任何作用。每个其他控制器都工作正常。

如果有帮助,有两种状态使用相同的控制器和模板,如下所示:

//initiate payment tx 
    .state('rec', {
      url: '/receive',
      templateUrl: 'views/rec.html',
      controller: 'RecCtrl'
    })

    //claim payment tx 
    .state('claim', {
      url: '/claim',
      templateUrl: 'views/rec.html',
      controller: 'RecCtrl'
    })

我使用$state.current.name分隔函数。但我试图删除另一个,它仍然没有工作。其他控制器工作正常。

1 个答案:

答案 0 :(得分:7)

ng-if创建了一个新范围。因此,您不能直接使用原始值,请使用参考值。

如果使用原始值,它们将是ng-if范围的本地值。因此,您无法从控制器访问它们。

如果您使用引用值,ng-model会检查ng-if范围中是否存在该值,如果不存在,那么它会查找父范围中的值,在此情况下为RecCtrl范围

这个link将帮助您了解为什么要使用参考值。

angular.module('myapp')
   .controller('RecCtrl', function($scope, $state, $rootScope, $http) {
      // use a reference value
      $scope.details={};
      $scope.submitForm = function(){
         console.log($scope.details.amount);   
      }
   })

HTML

<input ng-model='details.amount'> {{details.amount}} 
<button ng-click='submitForm()'>Submit</button>