Joh*_*ter 7 ruby-on-rails angularjs
我有两个具有多对多关联的模型 - 角色具有许多权限,同样权限可能属于多个角色.
现在我有一个允许用户创建新角色的视图; 我想为他们添加一个功能,让他们可以选择角色拥有哪些权限,以及创建/删除权限并分配权限.这就是我现在正在看的内容:
现在我在每个角色中嵌套当前分配的权限:
{
id: 1,
name: "Manager",
permissions: [
{
id: 2,
name: "Send Email"
}
]
}
Run Code Online (Sandbox Code Playgroud)
MyApp.factory('Role', function($resource) {
var Role = $resource('roles/:id', {id: '@id'}, {});
return Role;
}).factory('Permission', function($resource) {
var Permission = $resource('permissions/:id', {id: '@id'}, {});
return Permission;
});
function RoleCtrl($scope, $routeParams, Role, Permission) {
$scope.role = Role.get({id: $routeParams.id });
$scope.permissions = Permission.query();
$scope.role.save = function() {
$scope.role.$update(
function() { /* success */ },
function(response) { /* errors */ }
);
};
$scope.hasPermission = function(permission) {
return _.find($scope.role.permissions, function(p) {
return p.id == permission.id;
}) !== undefined;
};
}
Run Code Online (Sandbox Code Playgroud)
<div ng-controller="RoleCtrl">
<form ng-submit="save()">
<input type="text" ng-model="role.name">
<button type="submit">Submit</button>
<ul>
<li ng-repeat="permission in permissions">
<label class="checkbox">
<input type="checkbox" value="{{permission.name}}" ng-checked="hasPermission(permission)">{{permission.name}}
</label>
</li>
</ul>
</form>
</div>
Run Code Online (Sandbox Code Playgroud)
到目前为止,我所完成的只是正确设置复选框的初始值,但我有一种感觉,我可能会以错误的方式进行此操作.我对Angular很新,所以我想弄清楚最好的方法是什么:
小智 1
对于第一部分(现在没有足够的时间来思考第二部分,稍后再回来):
我会编写一个函数来更新控制器中的权限,该函数使用 ng-click 进行绑定。该函数接收权限和正在编辑的角色,并添加/删除正在编辑的权限。
function RoleCtrl($scope, $routeParams, Role, Permission) {
$scope.togglePermission = function(role,permission){
if($scope.hasPermission(permission){
// get the index of this permission role
$scope.role.permissions.splice(index,1);
}else{
$scope.role.permissions.push(permission)
}
}
}
Run Code Online (Sandbox Code Playgroud)
你的观点可能看起来像这样
<li ng-repeat="permission in permissions">
<label class="checkbox" ng-click="togglePermission(role,permission)">
<input type="checkbox" value="{{permission.name}}" ng-checked="hasPermission(permission)">{{permission.name}}
</label>
</li>
Run Code Online (Sandbox Code Playgroud)