在下面的代码中,当变量$watch更改时,recalculateInfoBox应该执行函数scores。然而,它什么也做不了。
我已经阅读了添加true作为$watch的第三个变量,通常可以解决这个问题,但是在这种情况下,$watch仍然不会触发。
,我还需要更改什么以使$watch触发?
<html ng-app="mainModule">
<head>
<style type="text/css">
</style>
</head>
<body ng-controller="mainController" >
<div>Scores: <input type="text" ng-model="scores" ng-list style="width:500px" placeholder="Enter comma-separated list..."/></div>
<div>You have {{scores.length}} items.</div>
<hr/>
ng-style:
<div ng-style="{'width': infoBox.width, 'background-color': infoBox.backgroundColor}">
This is the info.
</div>
<button ng-click="infoBox.width = '300px'">small</button>
<button ng-click="infoBox.width = '800px'">large</button>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script>
var mainModule = angular.module('mainModule', []);
function mainController($scope) {
$scope.scores = [];
$scope.infoBox = {width: '300px', backgroundColor: '#ddd'};
var recalculateInfoBox = function () {
console.log('in recalc');
$scope.infoBox.width = '100px';
};
$scope.$watch('scores', 'recalculateInfoBox', true);
}
</script>
</body>
</html>发布于 2015-01-06 16:28:29
$scope.$watch接受一个回调函数(而不是一个函数的名称)。
因此,改变到这个应该是有效的:
var recalculateInfoBox = function () {
console.log('in recalc');
$scope.infoBox.width = '100px';
};
$scope.$watch('scores', recalculateInfoBox, true);来自医生们
$watch(watchExpression,侦听器,objectEquality); 每当watchExpression更改时,注册要执行的侦听器回调。
发布于 2015-01-06 16:28:45
这个问题不是因为对象相等,而是因为监听程序必须是函数引用,而不是函数的名称。与作用域属性计算不同,它是第一个参数(通常以字符串形式提供),角甚至不从作用域计算函数(即使将该方法添加为作用域对象的属性)。
$scope.$watch('scores', 'recalculateInfoBox', true);应该是
$scope.$watch('scores', recalculateInfoBox, true);
angular.module('app', []).controller('ctrl', function($scope) {
$scope.scores = [];
$scope.infoBox = {
width: '300px',
backgroundColor: '#ddd'
};
var recalculateInfoBox = function() {
console.log(arguments);
$scope.infoBox.width = '100px';
};
$scope.$watch('scores', recalculateInfoBox);
});<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<div>Scores:
<input type="text" ng-paste="handlePaste($event)" ng-model="scores" ng-list style="width:500px" placeholder="Enter comma-separated list..." />
</div>
<div>You have {{scores.length}} items.</div>
<hr/>ng-style:
<div ng-style="{'width': infoBox.width, 'background-color': infoBox.backgroundColor}">
This is the info.
</div>
<button ng-click="infoBox.width = '300px'">small</button>
<button ng-click="infoBox.width = '800px'">large</button>
</div>
在处理ng-list时,您甚至可能不需要对象相等,也就是说,$scope.$watch('scores', recalculateInfoBox);也应该工作。
https://stackoverflow.com/questions/27802843
复制相似问题