AngularJS $ watch不适用于绑定对象

时间:2017-08-27 04:16:07

标签: angularjs

我想像这里一样实现相同的行为 Angular Material md-select Displaying quantity selected  (计算多项选择中的所选项目) 但它不起作用,这是我的代码和小提琴:

<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/ 提前谢谢。

1 个答案:

答案 0 :(得分:2)

您应该使用完全相同的 $scope 变量进行观看,它应该只是 selectedToppings

也应该是

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

而不是

$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