Angular watchCollection 绝对不起作用

Angular watchCollection absolutely doesn't work

控制器:

 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}} 但控制器不记录任何内容!我几乎尝试了所有方法,但仍然一无所获...我在控制台中只有一个日志 "work",它是在刷新页面之后。但是换了模型之后就什么都没有了...

这是因为你的对象的结构 - 你有一个对象数组的对象......而 $watchCollection 执行以下操作:

Shallow watches the properties of an object and fires whenever any of the properties change (for arrays, this implies watching the array items; for object maps, this implies watching the properties).

excerpt from here

最简单的解决方案可能只是为数组中的每个对象设置一个 $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");
      });
    }

});
<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>

或者,如果您使用的是 Angular 1.3+,则可以改用 $watchGroup