2016-02-23 41 views
0

$ watch我试图了解问题出在我使用的$ 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> 

,并在控制器我打电话$手表这一观点,这应该是我soppose 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永远不会被填充。我看到了使用此解决方案的其他stackoverflow示例,例如AngularJS: $watch for a select input。 谢谢你指点我正确的方向!

+0

从内存,如果它是你在看一个数组,你需要做一些额外的。例如,观察长度变化或做一个深入的观察,像http://stackoverflow.com/questions/14712089/how-to-deep-watch-an-array-in-angularjs – Arkiliknam

回答

1

当你看起来是$watch项目的数组,尝试指定true为您的手表通话中的第三个参数,以便它深入观察。

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

或者,尝试$watchCollection

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

FYI这已经在这里讨论:How to deep watch an array in angularjs?

+0

谢谢@Arkiliknam,我试过了,它没有' t工作...奇怪的是我有另一个选择在页面中,对于这一个观察者正在工作...我会再次检查... – Paolof76

+0

我不知道你使用的MultiSelect指令。也许问题在于它呢?我喜欢将绑定直接记录到页面以查看正在发生的事情,只需输出{{selectedItems}}即可。如果你这样做,你可以看到收藏随着你的改变而改变吗?也许它会给你一些线索,或者指出要看什么 – Arkiliknam

0

Sample,Sample2参考这两个环节。我也面临同样的问题。试试这对我来说工作得很好......你应该在ng模型中使用点。即NG-模型=“user.FirstName”

$scope.user = {}; 

    $scope.$watch('user.FirstName', function() { 
     console.log("FirstName") 
    }); 
相关问题