【问题标题】:Angular $scope variables not updating in controller角度 $scope 变量未在控制器中更新
【发布时间】:2017-02-17 07:53:51
【问题描述】:

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

在视图中我有这个代码

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

【问题讨论】:

  • 这个$scope.submitForm(){}不应该是$scope.submitForm = function(){}
  • @RaviTeja 这是一个错字。我已经更新了,谢谢。
  • 您的 HTML 文件中有 ng-ifng-repeatng-include 或其他指令吗?我可以展示你的完整 html,它会有所帮助。
  • 是的,我有 ng-if。这就是我区分这两个状态的方式。我已经更新了代码以显示 html @RaviTeja 的其余部分

标签: javascript angularjs


【解决方案1】:

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>

【讨论】:

  • 成功了,谢谢。我完全删除了 ng-if。太头疼了!
猜你喜欢
  • 1970-01-01
  • 2016-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-12
  • 1970-01-01
  • 2017-01-16
  • 1970-01-01
相关资源
最近更新 更多