在角度 md 中更改所选内容的状态时,$watch触发

$watch not fired when changing the state of the select in angular md

本文关键字:状态 触发 watch md      更新时间:2023-09-26

我试图了解我在使用 $scope.$watch 时的问题在哪里,但我无法弄清楚为什么没有触发手表中定义的函数。我在角度材料中有这个多选:

<md-select multiple ng-model="selectedItems" placeholder="Please select">
   <md-option ng-repeat="item in specialities" ng-value="item" ng-class="{'selected': item.selected}">
   <ng-md-icon class="checkboxfull" icon="check_box" size="18"></ng-md-icon>
   <ng-md-icon class="checkboxoutline" icon="check_box_outline_blank" size="18"></ng-md-icon>
   {{item.name}}
   </md-option>
</md-select>

在控制器中,我正在调用此视图的$watch,这应该是我反对 selectedItems:

    $scope.$watch('selectedItems', function(){
        console.log("$scope.selectedItems: ",$scope.selectedItems);
        $scope.filter.idList.length = 0;
        angular.forEach($scope.selectedItems, function (item) {
          $scope.filter.idList.push(item.id);
        });
        console.log("$scope.filter.idList: ",$scope.filter.idList);
   });

但永远不会访问日志,并且永远不会填充 $scope.filter.idList。我在堆栈溢出上看到了与此解决方案一起使用的其他示例,例如AngularJS:$watch用于选择输入。谢谢你为我指出正确的方向!

当您似乎正在$watch一系列项目时,请尝试为监视调用中的第三个参数指定true,以便对其进行深度监视。

scope.$watch('data', function (newVal, oldVal) { /*...*/ }, true);

或者,尝试$watchCollection

scope.$watchCollection('data', function (newVal, oldVal) { /*...*/ });

仅供参考,这里已经讨论了:如何在 angularjs 中深度观察数组?

样本, 样本 2 引用两个链接。 我也面临同样的问题。试试这个它对我来说工作正常..你应该在ng模型中使用点。即 ng-model="user.名字"

$scope.user = {};
    $scope.$watch('user.FirstName', function() {
        console.log("FirstName")
    });