Angular $scope变量在控制器中未更新。
Angular $scope变量在控制器中未更新。
我的变量在控制器中没有更新,我不知道为什么。
在视图中,我有以下代码:
{{amount}} {{txcode}}
在控制器中:
angular.module('myapp') .controller('RecCtrl', function($scope, $state, $rootScope, $http) { $scope.submitForm = function(){ console.log($scope.amount); // 返回undefined } })
我遵循了这个答案,并通过从视图中将amount
传递给submitForm()
来解决了它。 但现在我需要使用$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
来区分函数。但我尝试删除另一个状态,它仍然不起作用。其他控制器都工作正常。
Angular $scope variables not updating in controller
在Angular中,当使用ng-if
创建一个新的作用域时,无法直接使用原始值,而应该使用引用值。
如果使用原始值,它们将局限于ng-if
作用域中,无法从控制器中访问它们。
如果使用引用值,ng-model
会检查该值是否存在于ng-if
作用域中,如果不存在,则会在父作用域(在这种情况下是RecCtrl
作用域)中查找该值。
这个链接将帮助您理解为什么应该使用引用值。
以下是解决方法的示例代码:
angular.module('myapp') .controller('RecCtrl', function($scope, $state, $rootScope, $http) { // 使用引用值 $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
。