如何从另一个控制器检查复选框

时间:2014-08-11 08:07:30

标签: javascript angularjs checkbox

我有一个复选框列表,需要统计选中的复选框。

<div id="list" ng-controller = "listContr as ilist">
  <ul>
    <li ng-repeat = "item in ilist.items| filter: searchText">
      <input type = "checkbox" ng-model="item.done" id="ch">
    </li>
  </ul>
</div>

在我的项目中,我尝试使用另一个控制器获取此值。它也很复杂,因为这个值应该动态改变。

2 个答案:

答案 0 :(得分:0)

<script>

$(document).ready(function()
                    {
                       //Method 1:

                       alert($('.checkbox_class_here :checked').size());

                       //Method 2:

                       alert($('input[name=checkbox_name]').attr('checked'));

                       //Method: 3

                       alert($(":checkbox:checked").length);


                    });

</script>

答案 1 :(得分:0)

请参阅此处http://jsbin.com/guzaco/2/edit

您可以使用角度服务在控制器之间共享数据。

<强> JS:

var app = angular.module('app', []);

app.service("dataService", function(){

    var _items = [    
      {id:1, done:false},
      {id:3, done:true},
      {id:2, done:false}

  ];



  return {

    items:_items,


  };
});
app.controller('firstCtrl', function($scope,$filter,dataService){
 $scope.items = dataService.items;

  $scope.$watch('items', function(){

    $scope.count = ($filter('filter')($scope.items, {done:true})).length;

  }, true);




});

app.controller('listContr', function($scope,dataService){

 $scope.data = dataService;
});

<强> HTML:

<body ng-app="app">
  <div ng-controller="firstCtrl">
    <p>First Controller</p>
     Count: {{count}}

      </div>

  <div id="list" ng-controller = "listContr">
      <p>List Controller</p>

  <ul>
    <li ng-repeat = "item in data.items| filter: searchText">
      <input type = "checkbox" ng-model="item.done" id="ch">
    </li>
  </ul>


</div>
</body>