【问题标题】:Angular watchCollection absolutely doesn't workAngular watchCollection 绝对不起作用
【发布时间】:2015-07-05 16:20:58
【问题描述】:

控制器:

 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}} 但控制器没有记录任何内容!我几乎尝试了一切,但仍然一无所获......我在控制台中只有一个日志“工作”,它在刷新页面之后。但是在改变模型之后完全没有......

【问题讨论】:

    标签: angularjs watch


    【解决方案1】:

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

    Shallow 监视对象的属性并在任何属性更改时触发(对于数组,这意味着监视数组项;对于对象映射,这意味着监视属性)。

    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

    【讨论】:

      猜你喜欢
      • 2011-04-19
      • 2015-08-29
      • 1970-01-01
      • 1970-01-01
      • 2013-07-06
      • 2016-12-28
      • 2012-06-26
      • 2015-09-29
      相关资源
      最近更新 更多