How do I count the number of items selected in a directive?

If you have a career-box directive like this:

{{ career.name }}

The directive:

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;
        }
    }
  }
 };
});

Every time a career-box is selected I would like to count the total number of career-boxes selected (selected=true) and enable a button if they are more than 0.

How can I do that in the code?

There is no need to write a custom directive. It can be done with Angular core directives:

vm.selectedCount = function(item) {
    var count=0;
    for (let i=0; i<vm.careers.length; i++) {
      if (vm.careers[i].selected) count++;
    }
    return count;
  }
{{ career.name }}

Selected count: {{selectedCount()}}

The DEMO on PLNKR

The 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;
  }
})
  
    

Selected Div Example

{{ career.name }}

Selected count: {{selectedCount()}}
Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » How do I count the number of items selected in a directive&quest;

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录