Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic ng-model in ng-repeat

Using Angular JS, I have this object

var pages = [ 
    { name: 'users', title : "Users" }, 
    { name: 'roles', title : 'Roles' }
];

I'm trying to create a page for user roles. For that I need 4 checkboxes for each page. Each page must have 4 rules. Access, show, edit, delete.

Displaying pages in a ng-repeat

<div ng-controller='PageCtrl'>
   <ul>
     <li ng-repeat='page in pages'>
        {{ page.title }}
        <input type="checkbox" name="access"> Access
        <input type="checkbox" name="show"> Show
        <input type="checkbox" name="edit"> Edit
        <input type="checkbox" name="delete"> Delete
     </li>
   </ul>
</div>

So I need to pass those checkboxes values to the $scope. How can I bind a model for each checkbox?

Like this

<input type="checkbox" name="access" ng-model='page.name+_access'> Access

Checkbox model name should start with page.name. Like users_access, users_show...

like image 431
Rasit Avatar asked Mar 16 '23 16:03

Rasit


1 Answers

You can use the following syntax:

ng-model="page[page.name+'_access']"

But as a matter of fact, it looks one can move those groups into controller as well, then use another ng-repeat. Like this:

HTML:

<div ng-controller="PageCtrl">
    <ul>
        <li ng-repeat='page in pages'>{{ page.title }}
            <label ng-repeat="right in rights">
                <input type="checkbox" ng-model="page[page.name + '_' + right]" name="{{right}}" />{{right|capitalize}}</label>
            <button ng-click="log(page)">Log</button>
        </li>
    </ul>
</div>

JS:

var module = angular.module('myAp', [])
    .controller('PageCtrl', ['$scope', function ($scope) {
    $scope.pages = [{
        name: 'users',
        title: "Users"
    }, {
        name: 'roles',
        title: 'Roles'
    }];
    $scope.rights = ['access', 'show', 'edit', 'delete'];

    $scope.log = function (page) {
        console.log(page);
    }
}]).filter('capitalize', function() {
    return function (value) {
        return value.charAt(0).toUpperCase() + value.slice(1);
    };
});

Demo.

like image 90
raina77ow Avatar answered Mar 28 '23 12:03

raina77ow