如何计算指令中选择的元素数量?

时间:2017-04-13 15:54:12

标签: angularjs directive

如果你有这样的职业框指令:

<div ng-repeat='career in careers' career-box ng-click="toggleSelected()"> {{ career.name }} </div>

指令:

app.directive('careerBox', function() {
   return {
   restrict: 'A',
   link: function(scope, element, attrs) { 
     scope.selected = false, 

     scope.toggleSelected = function() { 
        element.toggleClass('selected'); 
        if(scope.selected) { 
            scope.selected = false; 
        } else { 
            scope.selected = true; 
        } 
    } 
  }
 };
});

每次选择职业框时,我都会计算所选择的职业框总数(选择=真),如果超过0则启用一个按钮。

我如何在代码中执行此操作?

2 个答案:

答案 0 :(得分:0)

首先,您需要一个具有multiple属性的select元素:

<select name="carers" multiple id="multipleCarers" ng-model="data.multipleCarers">
  <option ng-repeat="career in careers" value="{{career.value}}">
    {{career.name}}
  </option>
</select>

之后,您可以获得所选选项的数量:

{{data.multipleCarers.length}}

答案 1 :(得分:0)

无需编写自定义指令。可以使用Angular核心指令完成:

  vm.selectedCount = function(item) {
    var count=0;
    for (let i=0; i<vm.careers.length; i++) {
      if (vm.careers[i].selected) count++;
    }
    return count;
  }
<div ng-repeat='career in careers' 
     ng-click="career.selected = !career.selected"
     ng-style="{'background-color': career.selected?'yellow':''}"> 
 {{ career.name }} 
</div>

<hr>Selected count: {{selectedCount()}}

DEMO on PLNKR

DEMO

angular.module("myApp",[]);

angular.module("myApp").controller("myVm", function($scope) {
  var vm = $scope;
  vm.careers = [ {name: "Police Officer", value: 1},
                 {name: "Nurse", value:2},
                 {name: "Doctor", value:3},
               ];
  vm.selectedCount = function(item) {
    var count=0;
    for (let i=0; i<vm.careers.length; i++) {
      if (vm.careers[i].selected) count++;
    }
    return count;
  }
})
  <script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="myApp" ng-controller="myVm">
    <h1>Selected Div Example</h1>
    <div ng-repeat='career in careers' 
         ng-click="career.selected = !career.selected"
         ng-style="{'background-color': career.selected?'yellow':''}"> 
     {{ career.name }} 
    </div>
  
    <hr>Selected count: {{selectedCount()}}
    
  </body>