控制器:
app.controller('SettingsController', function ($scope, $http) {
$scope.openingtimes = {
"times": [
{"id":1,"day":1,"name_of_day":"Pondělí","open_from":"13:00","open_to":"16:00"},
{"id":2,"day":1,"name_of_day":"Pondělíadas","open_from":"13:00","open_to":"16:02"},
{"id":3,"day":1,"name_of_day":"Pondělí","open_from":"13:00","open_to":"16:00"},
{"id":4,"day":1,"name_of_day":"Pondělísf","open_from":"13:00","open_to":"16:00"}
]};
$scope.$watchCollection('openingtimes.times', function () {
console.log("work");
});
});
查看:
<div class="angular" ng-controller="SettingsController">
<div ng-repeat="time in openingtimes.times">
<input type="text" ng-model="time.name_of_day"/> {{ time.name_of_day }} : {{ time.open_from | openingTime }} - {{ time.open_to | openingTime }}
</div>
当我键入输入模型正在改变时一切正常,因为我在这里看到它:{{time.name_of_day}}但是控制器没有记录任何东西!我几乎尝试了一切,但仍然没有...我在控制台中只有一个日志“工作”,它是在刷新页面之后。但改变模型后绝对没有...
答案 0 :(得分:2)
由于你的对象的结构 - 你有一个对象数组的对象......而$watchCollection
执行以下操作:
Shallow监视对象的属性,并在任何属性发生更改时触发(对于数组,这意味着要观察数组项;对于对象映射,这意味着要观察属性)。
最简单的解决方案可能只是为数组中的每个对象设置$watchCollection
:
angular.module('app', [])
.controller('SettingsController', function ($scope, $http) {
$scope.openingtimes = {
"times": [
{"id":1,"day":1,"name_of_day":"Pondělí","open_from":"13:00","open_to":"16:00"},
{"id":2,"day":1,"name_of_day":"Pondělíadas","open_from":"13:00","open_to":"16:02"},
{"id":3,"day":1,"name_of_day":"Pondělí","open_from":"13:00","open_to":"16:00"},
{"id":4,"day":1,"name_of_day":"Pondělísf","open_from":"13:00","open_to":"16:00"}
]};
for(var i in $scope.openingtimes.times) {
$scope.$watchCollection('openingtimes.times[' + i + ']', function () {
console.log("work");
});
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="angular" ng-app="app" ng-controller="SettingsController">
<div ng-repeat="time in openingtimes.times">
<input type="text" ng-model="time.name_of_day"/> {{ time.name_of_day }} : {{ time.open_from }} - {{ time.open_to }}
</div>
&#13;
或者,如果您正在使用Angular 1.3+,则可以使用$watchGroup
代替。