I'm currently building a CRUD for my app admin. I'm using AngularJS with a RESTfull API. I can sucessfully save a simple model. But when I have Many-to-many relationship I'm a bit lost when it comes to set the update/create form. I have build a Plunker to showcase the attempt: http://plnkr.co/edit/okeNuYBJ5f33gtu6WBoW
Now using checkbox instead of dropdown as Jason suggested:
http://plnkr.co/edit/okeNuYBJ5f33gtu6WBoW
But my problem #3 is still not fixed. How can I save those updated/created relationships?
So I have that User model that has a Many-to-Many relationship with a Role model. I am able to display/list the model with its relationship. When editing a User I load all Roles so UI can build a dropdown of Roles to be selected. I want to have as many dropdown as there is a relationship. So I nested my dropdown in a repeat="userRole in user.role".
When doing an update
First problem: if a user has many roles it display as many dropdown as there is but the selected role for each one is the first relationship.
Second problem: I have a button to add a new role to the loaded user. I'm not sure I made it right since when saving I don't see any trace of the new attached role.
Third problem: when saving I loose the connection from my roles. Only the user is updated. My form is wrong but where is the problem?
When doing a create
I'm not able to link a role to a new user. When I clic on "Add a new role" the first role of the Roles list is pushed to the user. But user is not yet created. So I get an error. Once again my form is wrong. What is the error? When saving a new user how can I also POST the related roles?
Here is some code in case the Plunker doesn't work:
index.html
<!DOCTYPE html>
<html lang="en" xmlns:ng="http://angularjs.org" data-ng-app="CRUD">
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.1.1/css/bootstrap.no-icons.min.css" />
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/font-awesome/2.0/css/font-awesome.css" />
</head>
<body>
<div class="span6" ng-view></div>
<script src="http://code.angularjs.org/1.1.0/angular.min.js"></script>
<script src="http://code.angularjs.org/1.1.0/angular-resource.js"></script>
<script src="/crud.js"></script>
</body>
</html>
crud.js My AngularJS specific code
var users = [
{'id':1,'name':'User 1', 'role':[{'id':1,'name':'Role 1'},{'id':2,'name':'Role 2'}]},
{'id':2,'name':'User 2', 'role':[{'id':2,'name':'Role 2'}]},
{'id':3,'name':'User 3', 'role':[{'id':1,'name':'Role 1'}]},
{'id':4,'name':'User 4', 'role':[{'id':3,'name':'Role 3'},{'id':2,'name':'Role 2'}]}
];
var roles = [
{'id':1,'name':'Role 1'},
{'id':2,'name':'Role 2'},
{'id':3,'name':'Role 3'}
];
/* Route */
angular.module('CRUD', []).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/create', {templateUrl: 'create.html',controller: ctrlCreate}).
when('/read', {templateUrl: 'read.html',controller: ctrlRead}).
when('/update/:userId', {templateUrl: 'update.html', controller: ctrlUpdate}).
otherwise({redirectTo: 'read'});
}]);
/* Controller CREATE */
function ctrlCreate($scope, $http, $location) {
// dirty hack to find the user to update (in real life it would be loaded via REST)
$scope.user = null;
$scope.roles = roles;
$scope.save = function() {
// dirty hack to change the user (in real life it would be trigger a POST request to the server with updated model)
users.push($scope.user);
//if a scope digestion is already going on then it will get picked up and you won't have to call the $scope.$apply() method
if(!$scope.$$phase) { //this is used to prevent an overlap of scope digestion
$scope.$apply(); //this will kickstart angular to recognize the change
}
$location.path('/');
};
$scope.addRole = function(){
$scope.user.role.push(roles[0]);
};
}
ctrlCreate.$inject = ['$scope','$http','$location'];
/* Controller READ */
function ctrlRead($scope, $http, $location) {
// dirty hack to find the user to update (in real life it would be loaded via REST)
$scope.users = users;
$scope.roles = roles;
}
ctrlRead.$inject = ['$scope','$http','$location'];
/* Controller UPDATE */
function ctrlUpdate($scope, $http, $location, $routeParams) {
$scope.user = null;
$scope.roles = roles;
var id=$routeParams.userId;
// dirty hack to find the user to update (in real life it would be loaded via REST)
for (var i = 0; i < users.length; i++) {
if (users[i].id==id) {
$scope.user=users[i];
console.debug($scope.user.role);
}
}
$scope.save = function() {
// dirty hack to change the user (in real life it would be trigger a PUT request to the server with updated model)
for (var i = 0; i < users.length; i++) {
if (users[i].id==id) {
users[i] = $scope.user;
}
}
//if a scope digestion is already going on then it will get picked up and you won't have to call the $scope.$apply() method
if(!$scope.$$phase) { //this is used to prevent an overlap of scope digestion
$scope.$apply(); //this will kickstart angular to recognize the change
}
$location.path('/');
};
$scope.addRole = function(){
$scope.user.role.push(roles);
console.debug($scope.user.role);
};
}
ctrlUpdate.$inject = ['$scope','$http','$location', '$routeParams'];
Now my templates:
create.html
<form>
<div class="control-group">
<label class="control-label">Name</label>
<input type="text" ng-model="user.name" placeholder="Enter a name here">
</div>
<div ng-repeat="userRole in user.role">
<div class="control-group">
<label class="control-label">Role</label>
<select ng-selected="userRole.id">
<option ng-repeat="role in roles" value="{{role.id}}">{{role.name}}</option>
</select>
</div>
</div>
<button ng-click="addRole()">Attach another role</button>
<br />
<br />
<input type="submit" value="Submit" ng-click="save()" class="btn btn-primary">
<a href="#/" class="btn">Cancel</a>
</form>
read.html
<br />
<table class="table table-bordered table-striped table-centred table-condensed table-hover">
<thead>
<tr>
<th>User Name</th>
<th>Role Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users">
<td>{{user.name}}</td>
<td>
<span ng-repeat="role in user.role">{{role.name}}</span>
</td>
<td>
<a title="edit" href="#/update/{{user.id}}"><i class="icon-edit"></i></a>
</td>
</tr>
</tbody>
</table>
<br />
<a href="#/create" class="btn btn-primary"><i class="icon-plus"></i> Create a new user</a>
update.html
<form>
<div class="control-group">
<label class="control-label">Name</label>
<input type="text" ng-model="user.name" placeholder="Enter a name here">
</div>
<div ng-repeat="userRole in user.role">
<div class="control-group">
<label class="control-label">Role</label>
<select ng-selected="userRole.id">
<option ng-repeat="role in roles" value="{{role.id}}">{{role.name}}</option>
</select>
</div>
</div>
<button ng-click="addRole()">Attach another role</button>
<br />
<br />
<input type="submit" value="Submit" ng-click="save()" class="btn btn-primary">
<a href="#/" class="btn">Cancel</a>
</form>
Please made advice if you see some bad coding or wrong architecture (I think I could do some directive for instance when it comes to add a new role maybe?). I hope this is clear enough. Thanks!
You can solve the first 2 problems you are having by redesigning your UI. Instead of using dropdowns use a checkbox field. Example plnkr: http://plnkr.co/edit/hgq2hmbRty7B9oryQnkm
Once you have less moving parts on your page, hopefully it will be easy to debug the 3rd problem.