“角度”复选框选择全部元素或从表中选择单个元素



我这里有两种情况,一种是用户单击单个元素并提交,另一种是用户单击全选按钮并提交,以便根据用户的要求,我想在控制器中获取项目的详细信息。

这是我的代码

.HTML

        <div >
          <label class="btn btn-info">
            <input ng-model="vm.selectAll" type="checkbox"  name="selectAll" value="allitems" > Select all Items
          </label>
          <button ng-click="vm.purchaseItems(item)" class="btn btn-danger" type="submit" >Purchase selected Items</button>
       <table ng-repeat="item in vm.items">
          <tbody>
              <thead>
                <th ><input type="checkbox" ng-checked="vm.selectAll"/></th>
                <th >Student Id</th>
                <th >Name</th>
                <th >School</th>
             </thead>
              <tr>
                <td></td>
                <td >{{item.studentId}}</td>
                <td >{{item.name}}</td>
                <td >{{item.schoolName}}</td>
            </tr>
            </tbody>
        </table>
     </div>

控制器

 vm.purchaseItems = purchaseItems;
  function purchaseItems(item) {
  console.log(item); 
// I want to log only selected items either single or all based on user call
}

我应该使用指令还是可以在控制器本身中完成?

您需要一个变量来保存所选值,然后需要一个过滤器函数来返回结果,请参阅小提琴 http://jsfiddle.net/SNF9x/296/

this.setUnsetAll = function(selected){
 this.items.forEach(function(ele){
  ele.isSelected = selected;
 }); 
}
this.purchaseItems = function(){
var selectedItems = this.items.filter(function(ele){
return (ele.isSelected);
});
console.log(selectedItems)
}