$ scope。$ watch not firing(controller as vm)

时间:2018-01-16 18:02:33

标签: javascript angularjs

无论我从同一个问题的答案中尝试过什么,我都无法解决这个问题。 请注意我还使用tr-state checkbox directive

https://plnkr.co/edit/mBy0mm0XZNzo9EnsmL9Q?p=preview



var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  var vm = this;
  
   vm.flags = [
        { field: "PaymentMade", title: "Payment Made", isSeaAir: false, filter: null },
        { field: "isInTransit", title: "In Transit", isSeaAir: false, filter: null },
        { field: "Docked", title: "Docked", isSeaAir: false, filter: null },
        { field: "isDockedPartial", title: "Docked Partial", isSeaAir: true, filter: null },

    ];
  $scope.$watch('vm.flags' , function handleFlagssChange(newVla, oldVal) {
        console.log("flags changed");
    });
});

app.directive('indeterminate', [function () {
    return {
        require: '?ngModel',
        link: function (scope, el, attrs, ctrl) {
            var truthy = true;
            var falsy = false;
            var nully = null;
            ctrl.$formatters = [];
            ctrl.$parsers = [];
            ctrl.$render = function () {
                var d = ctrl.$viewValue;
                el.data('checked', d);
                switch (d) {
                    case truthy:
                        el.prop('indeterminate', false);
                        el.prop('checked', true);
                        break;
                    case falsy:
                        el.prop('indeterminate', false);
                        el.prop('checked', false);
                        break;
                    default:
                        el.prop('indeterminate', true);
                }
            };
            el.bind('click', function () {
                var d;
                switch (el.data('checked')) {
                    case falsy:
                        d = truthy;
                        break;
                    case truthy:
                        d = nully;
                        break;
                    default:
                        d = falsy;
                }
                ctrl.$setViewValue(d);
                scope.$apply(ctrl.$render);
            });
        }
    };
}]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="plunker" ng-controller="MainCtrl as vm">
  <label>Flags: </label>
        <label class="btn btn-info" ng-repeat="f in vm.flags" style="margin-right:5px;">
            <input type="checkbox" ng-model="f.filter" indeterminate />
            {{f.title}} | {{f.filter}}
        </label>
</body>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您需要添加第三个参数true,以检查对象是否正确。

$scope.$watch('vm.flags' , function handleFlagssChange(newVla, oldVal) {
    console.log("flags changed");
}, true);

Angular documentation

  

当objectEquality == true时,watchExpression的不等式是   根据angular.equals函数确定。保存价值   对于稍后比较的对象,使用angular.copy函数。   因此,这意味着观看复杂的物体会产生不利影响   记忆和表现的影响。