Add boolean checkboxes ng-model to object AngularJS

纵然是瞬间 提交于 2019-12-02 13:01:17

问题


I am trying to do something like tree-checkboxes. I would like to add boolean to children of checked name : ex. after click checkbox at name : eva - all her childrens will be also checked. Like that :

$scope.messages = 
    {

    "family": [

        {    
            "name": "eva",
            "checked" : true,
            "childrens": [    
                {    
                    "name": "John",
                    "checked" : true,
                    "childrens": [    
                        {    
                            "name": "Jacob",
                            "checked" : true,
                        }      

My code :

<div ng-repeat="key in messages">
  <ul ng-repeat=" (x, y) in key" style="list-style:none;">
    <li>
        <input type="checkbox" ng-model="y.check" ng-change="changeValue(shapes, y.name)" /> {{y.name}} {{y.check}}</li>
      <li style="margin-left:15px;" ng-repeat="(a,b) in y.childrens">
        <input type="checkbox" ng-model="b.check" ng-change="changeValue(shapes, b.name)" /> {{b.name}} {{b.check}}
        <ul style="margin-left:15px;" ng-repeat="p in b.childrens">
          <li>
            <input type="checkbox" ng-model="p.check" ng-change="changeValue(shapes, p.name)" /> {{p.name}} {{p.check}}</li>
        </ul>
    </li>
  </ul>
</div>

Here is my plnkr : http://plnkr.co/edit/lFYUvcTt1W709vam5Dfv?p=preview


回答1:


I forked your pinkr

As you can see, I update the childrens in the ng-change and this function is recursive so all childrens will be checked aswell

$scope.changeValue = function(foo, person) {
    for(var i in person.childrens){
      person.childrens[i].check = person.check;
      $scope.changeValue(foo, person.childrens[i]);
    }
};

If a person is checked, the children will be checked. If a child is check, it won't update the parent.



来源:https://stackoverflow.com/questions/51648812/add-boolean-checkboxes-ng-model-to-object-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!