【发布时间】:2015-03-04 08:48:27
【问题描述】:
在下面的代码中,$watch 应该在变量scores 发生变化时执行函数recalculateInfoBox。但是,它什么也没做。
我已经阅读了将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>
【问题讨论】:
-
另外,使用 ng-list 时不需要对象相等性