本文介绍了动态NG-模型NG重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

采用了棱角分明的JS,我有这样的对象

Using Angular JS, I have this object

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

我试图创建的用户角色的页面。对于我需要4个复选框的每一页。每个页面都要有4个规则。访问,显示,编辑,删除。

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.

在NG重复显示的页面

<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?

筛选

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

复选框型号名称应与page.name开始。像users_access,users_show ...

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

推荐答案

您可以使用下面的语法:

You can use the following syntax:

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

但作为事实上,它看起来可以将这些群体纳入控制器为好,然后用另一NG-重复。像这样的:

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);
    };
});

这篇关于动态NG-模型NG重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 14:35