saleh asadi saleh asadi - 3 months ago 11
AngularJS Question

how to bind the values of two different arrays with each other in angular js

hi i'm going to manage the user access levels with angular js and json.
i have two arrays one for menu structure and the other for access levels.


current access levels :


$scope.current_access_levels ={
"can_home":{"title":"home","value":true},
"can_mail":{"title":"mail","value":false}
};



menu structure :


$scope.menu = [
{"id":"1","name":"home","aclvl":"can_home"},
{"id":"2","name":"mail","aclvl":"can_mail"}
];


every menu field has an "aclvl" that matches with the names of objects in "current_access_level" array.


what i'm going to do is something like this :


<div ng-app="app" ng-controller="appCtrl">
<div ng-repeat="aclvl in current_access_levels">
<label>{{aclvl.title}}</label><input type="checkbox" value="1" ng-model="aclvl.value"/>
</div>
<br />
<br />
<ul>
<li ng-repeat="men in menu">
<input type="checkbox" ng-model="current_access_levels.(men.aclvl).value"/>{{men.aclvl}}
</li>
</ul>
</div>


for example if the "aclvl" of "men" is equal to "can_home" the checkbox value should be equal to "aclvl.can_home.value".
any body knows how should i handle this!?
i have added a fiddle to clear what i'm supposing to do.
thanks



angular.module('app',[])
.controller('appCtrl',function($scope){

$scope.current_access_levels ={"can_home":{"title":"home","value":true},"can_mail":{"title":"mail","value":false}};

$scope.menu = [{"id":"1","name":"home","aclvl":"can_home"},{"id":"2","name":"mail","aclvl":"can_mail"}];

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


<div ng-app="app" ng-controller="appCtrl">
<!-- current access levels -->
<p>current access levels</p>
<div ng-repeat="aclvl in current_access_levels">
<label>{{aclvl.title}}</label><input type="checkbox" value="1" ng-model="aclvl.value"/>
</div>
<!-- current access levels -->
<br />
<div>{{current_access_levels}}</div>
<br />
<hr>
<!-- menu structure just for example -->
<p>menu structure</p>
<ul>
<li ng-repeat="men in menu">
<input type="checkbox" ng-model="current_access_levels.can_home.value"/>{{men.aclvl}}
</li>
</ul>
<!-- menu structure just for example -->

</div>




Answer

You can use [] with current_access_levels it like as -

 <li ng-repeat="men in menu">
      <input type="checkbox" ng-model="current_access_levels[men.aclvl].value"/>{{men.aclvl}}
    </li>
Comments