0

I'm trying to understand where the issue is in my use of $scope.$watch, but I can't figure out why the function defined in the watch is not fired. I have this multiselect in Angular material:

<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>

and in the controller I'm calling the $watch for this view, that should be I 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);
   });

But the log is never reached and the $scope.filter.idList is never populated. I saw other examples on stackoverflow that are working with this solution, e.g. AngularJS: $watch for a select input. Thank you for pointing me on the right direction!

Community
  • 1
  • 1
Paolof76
  • 889
  • 1
  • 9
  • 23
  • From memory, if it's an array you're watching, you need to do a little extra. Eg, watch for length change or do a deep watch like http://stackoverflow.com/questions/14712089/how-to-deep-watch-an-array-in-angularjs – Arkiliknam Feb 23 '16 at 23:51

2 Answers2

1

As you seem to be $watching an array of items, try specifing true for the third argument in your watch call so that it does a deep watch.

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

Or alternatively, try $watchCollection

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

FYI This has been discussed here: How to deep watch an array in angularjs?

Community
  • 1
  • 1
Arkiliknam
  • 1,805
  • 1
  • 19
  • 35
  • thanks @Arkiliknam, I tried and it doesn't work... strangely enough I have another select in the page and for this one the watcher is working... I will double check again... – Paolof76 Feb 24 '16 at 00:19
  • I don't know the MultiSelect directive you're using. Perhaps the issues lies within it? I like to log bindings directly to the page to see what's going on, just outputting {{ selectedItems }}. If you do that, can you see the collection changing as you make changes? Perhaps it will give you a clue what's going on, or indicate what to $watch – Arkiliknam Feb 24 '16 at 09:50
0

Sample, Sample2 Ref both link. Me too face same problem. try this its working fine for me..You should use dot in ng-model. i.e ng-model="user.FirstName"

$scope.user = {};

    $scope.$watch('user.FirstName', function() {
        console.log("FirstName")
    });
Community
  • 1
  • 1
Suresh B
  • 1,658
  • 1
  • 17
  • 35