我的变量未在控制器中更新,我也不知道为什么。

在视图中我有此代码

<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分隔功能。但是我尝试删除另一个,但还是没用。其他控制器工作正常。

最佳答案

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>

关于javascript - Angular $ scope变量未在 Controller 中更新,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39932083/

10-09 23:13