I have two models with a many to many association -- a Role has many permissions, and likewise a permission may belong to multiple roles.
Right now I have a view which allows users to create new Roles; I'd like to add the ability for them to select which permissions a Role has, as well as create/delete permissions and assign them. Here's what I'm looking at right now:
Right now I'm nesting the currently assigned permission inside each role:
{
id: 1,
name: "Manager",
permissions: [
{
id: 2,
name: "Send Email"
}
]
}
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;
};
}
<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>
So far all I've accomplished is getting the initial values of the checkboxes set correctly, but I have a feeling I might be going about this the wrong way. I'm fairly new to Angular so I'm trying to figure out what the best way is to:
For first part(not enough time right now to think through the second part, will get back later):
I would write a function to update permissions in the controller, which is bound using ng-click. The function takes in the permission, and the role being edited, and adds/deletes the permission being edited.
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)
}
}
}
Your view would probably look something like this
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With