Alex Lavriv
Alex Lavriv

Reputation: 321

AngularJS $watch does not work with bind object

I would like to implement the same behaviour like here Angular Material md-select Displaying quantity selected (counting selected items in a multiple select ) But it does not work, here is my code and fiddle :

<div ng-app="selectDemoOptGroups" ng-controller="SelectOptGroupController" >
    <md-select md-selected-text="selectedText" ng-model="selectedToppings"  multiple>   
        <md-option ng-value="topping.name" ng-repeat="topping in toppings">{{topping.name}}</md-option>
    </md-select>
</div>


.module('selectDemoOptGroups', ['ngMaterial'])
.controller('SelectOptGroupController', function($scope) {

  $scope.toppings = [
    { category: 'meat', name: 'Pepperoni' },
    { category: 'meat', name: 'Sausage' },
    { category: 'meat', name: 'Ground Beef' },
    { category: 'meat', name: 'Bacon' },
    { category: 'veg', name: 'Mushrooms' },
    { category: 'veg', name: 'Onion' },
    { category: 'veg', name: 'Green Pepper' },
    { category: 'veg', name: 'Green Olives' }
  ];
  $scope.selectedToppings = [];       

  $scope.$watch("$scope.selectedToppings.length", function() {
      if ($scope.selectedToppings.length > 0){
            $scope.selectedText = $scope.selectedModel.length + " selected";
      }
      else {
            $scope.selectedText = "Toppings";
      }
  },true);
});

https://jsfiddle.net/AlexLavriv/ya6eu8kz/2/ Thank you in advance.

Upvotes: 2

Views: 123

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222522

You should use exactly the same $scope variable for watch, it should be just selectedToppings

also it should be

 $scope.selectedText = $scope.selectedToppings + " selected";

instead of

$scope.selectedModel.length + " selected";

CODE

  $scope.$watch("selectedToppings", function() {
       if ($scope.selectedToppings.length > 0){
          $scope.selectedText = $scope.selectedToppings + " selected";
        }
       else{
          $scope.selectedText = "Toppings";
       }
    },true);

WORKING FIDDLE

Upvotes: 3

Related Questions