2016-02-23 43 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") 
    }); 
相關問題