CRUD model with nested model - angularjs

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
EDIT:
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">
Cancel
</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 />
<i class="icon-plus"></i> Create a new user
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">
Cancel
</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.

Related

On Checking Check Box Get the child Object Angular Js

I want to achieve a scenario in which when i click TV1 radiobutton i want to get all of its children in the object i.e ProductName TV1, Number Of Channels 1 . Below is my code
Markup :
<div ng-repeat="product in ProductTypes">
<div ng-show="product.selected" ng-repeat="Product in product.ProductList">
<label>
<input type="radio" name="internetProduct{{$parent.$index}}"
ng-model="Product" ng-value="{{Product}}" ng-click="GetValue()" />
{{Product.ProductName}}
</label>
<table>
<tr ng-repeat="(key, val) in Product">
<td>{{key}}</td>
<td>{{val}}</td>
</tr>
</table>
</div>
</div>
Controller (js) :
var app = angular.module('ProductCatalog.controllers', ['ui.bootstrap'])
.controller('OfferCtrlr', function ($scope, $http, $modal) {
$scope.GetValue = function() {
var a = $scope.radio;
}
})
Right now, nothing is coming in $scope.radio. Please helpp.
You can pass the product instance to your ng-click function call as a parameter. So whenever the radio button is clicked, the corresponding product instance will be available inside your function. The below code will give you the instance for radio button. Do the same thing for checkbox, call a function on checking and pass the corresponding instance.(you have not provided the markup for checkbox)
HTML:
<div ng-repeat="product in ProductTypes">
<div ng-show="product.selected" ng-repeat="Product in product.ProductList">
<label>
<input type="radio" name="internetProduct{{$parent.$index}}"
ng-model="checked" ng-value="Product" ng-click="GetValue(Product)" />
{{Product.ProductName}}
</label>
<table>
<tr ng-repeat="(key, val) in Product">
<td>{{key}}</td>
<td>{{val}}</td>
</tr>
</table>
</div>
</div>
JS:
var app = angular.module('ProductCatalog.controllers', ['ui.bootstrap'])
.controller('OfferCtrlr', function ($scope, $http, $modal) {
$scope.GetValue = function(product) {
console.log(product);
}
})
Well, Load all the parent and child objects then show/hide through the AngularJS, through that you will achieve your scenario.

Angular Wiring up two controllers from Model to auto fill form

I've got an angular app I'm working on where I'm trying to auto fill a pop up modal based on a user's selection.
I thought I could use my model service to keep track of what the user selected and 'wire' the controller for the <select> list and it's edit button to the model but that doesn't seem to work.
Adding to the complexity I'm using angular-route and my <select> list is buried in a view. I was trying to keep my pop up modals in a separate controller outside the view because they've got their own templates and I had problems when I nested them into the view...
I've seen a few examples of wiring up angular apps and thought I understood them but I can't figure out what I'm doing wrong.
EDIT (thanks Pankaj Parkar for pointed out my mistakes in the plunker):
I have a plunker here:
https://plnkr.co/edit/6f9FZmV8Ul6LZDm9rcg9?p=preview
Below is the snipped in a single HTML page with CDN links :).
Am I just completely misunderstanding how angularjs is suppose to work?
<html ng-app="myApp">
<head>
<title>Bootstrap 3</title>
</head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<body>
<div ng-view></div>
<script id="editables.html" type="text/ng-template">
<div class="container">
<div class="jumbotron">
<form>
<div class="form-group">
<select class="form-control" id="mapsSelect" size="10" multiple ng-model="model.selected">
<option ng-repeat="n in editables">{{n}}</option>
<select>
</div>
<a href="#editModal" class = "btn btn-info" data-toggle="modal" ng-click="edit()" >Edit</a>
</form>
</div>
</div><!--end container div-->
</script>
<div ng-controller="modalsController">
<div id="editModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4>New Map</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="name" class="col-lg-3 control-label">Name</label>
<div class="col-lg-9">
<input type="text" class="form-control" id="name" ng-model="formModel.name"></input>
</div>
</div>
<div class="form-group">
<label for="desc" class="col-lg-3 control-label">Description</label>
<div class="col-lg-9">
<input type="text" class="form-control" id="desc" ng-model="formModel.desc"></input>
</div>
</div>
<div class="modal-footer">
<pre> {{ formModel | json }}<br><br>Working: {{ workingMap }}</pre>
Cancel
Continue
</div>
</form>
</div>
</div>
</div><!-- end modal -->
</div>
</body>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-route.min.js"></script>
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- <script src = "js/script.js"></script> -->
<script>
var app = angular.module('myApp', ['ngRoute']);
var modelService = function ($log){
var moduleHello = function(myMessage){
console.log("Module hellow from myService " + myMessage);
}
var moduleNames = {
"First" : {desc: "First's Description"},
"Second" : {desc: "Second's Description"},
"Third" : {desc: "Third's Description"}
};
var moduleWorkingName = {};
return {
hello: moduleHello,
editables: moduleNames,
workingName: moduleWorkingName
}
}//end modelService
app.factory("modelService", ["$log", modelService]);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/editables', {
controller: "editablesController",
templateUrl: "editables.html"
}).
otherwise({
redirectTo: "/editables"
});
}]);
app.controller('editablesController', ['$scope', '$log','modelService', function($scope,$log, $modelService) {
$scope.model = {};
//console.log( JSON.stringify( $modelService.editables ) );
$scope.editables = [];
for ( name in $modelService.editables){
$scope.editables.push( name );
}
$scope.edit = function(){
if ( typeof $modelService.editables [$scope.model.selected] != 'undefined'){
$modelService.workingName = $modelService.editables [$scope.model.selected];
console.log ("Setting my working name to " + JSON.stringify( $modelService.workingName ) );
}else{
console.log ("Nothing Selected");
}
}
}]);
app.controller('modalsController', ['$scope','modelService', function($scope,$modelService) {
$scope.formModel = {};
$scope.formModel.name = "Hard coding works of course";
$scope.formModel.desc = $modelService.workingName.desc; //But I can't seem to get this to update. I thought pointing it at an object in the Model would be enough.
console.log("Firing up modalsController");
}]);
</script>
</html>
I spent the last two days mulling over this in my head and I think I figured it out. For starters, here's the (working) plunker:
https://plnkr.co/edit/Kt3rebPtvGTt0WMXkQW4?p=preview
Now, the explanation. I was trying to keep a separate 'formModel' object that kept track of the controller's state. But that's both silly and pointless.
Instead what you're supposed to do is:
a. Create an object in your service to hold all your data (I just called this 'model')
b. For each controller that needs to share data create a variable on the $scope of the controller and point it to your 'model' variable from your service.
c. after that use the variables from your model in your html.
So in both my controllers you'll find this line:
$scope.model = $modelService.model;
and in my HTML you'll find stuff like this:
<input type="text" class="form-control" id="name" ng-model="model.workingName.name"></input>
notice how I'm using "model.workingName.name"? This references $scope.model.workingName.name, which thanks to the line $scope.model = $modelService.model from my JavaScript now points directly to my model.
And that is how you "wire up" Angular.
By the way, experienced Angular folks have probably noticed that this part:
$scope.editables = [];
for ( name in $modelService.model.names){
$scope.editables.push( name );
}
probably belongs in a directive instead of a controller because I'm editing the DOM.
Stuff like that's what makes it so hard to learn AngularJS. There's so many concepts to get the hang of.

Angularjs: ng-model not displaying properly

I have a parent and child controller relationship. This is a non-working mockup of the basic functionality. I'm sure anyone more competent than me can get it working for a Plunker or Fiddle model. (So there is probably something wrong with: $scope.data.contactList = [{ID: 1, Email: "someemail#email.com"}, {ID: 2, Email: "anotheremail#email.com"}];) I tried creating some objects for the contactList array.
Anyway. I want to be able to click a link in the second table in the code below to invoke EditShowContact. In my actual app, this will show a hidden div and it will obviously display more properties of a contact than just the email.
In my actual program, the values of the table are filled out properly (i.e. my ng-repeat directive is working fine), but I cant seem to get the ng-model directive to respond. I've tried various different ways and nothing seems to work.
<html ng-app="myApp"><head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('ContactsController', function ($scope)
{
this.currentContactID = null;
this.EditShowContact = function(intContactID)
{
this.currentContactID = intContactID;
//this.currentContact = $scope.data.contactList[intContactID]; unclear why this assignment fails
};
});
app.controller('ActionsController', function ($scope)
{ $scope.data = {};
$scope.data.contactList = [{ID: 1, Email: "someemail#email.com"}, {ID: 2, Email: "anotheremail#email.com"}];
});
</script>
</head>
<body ng-controller="ActionsController as ActCtrl">
<div ng-controller="ContactsController as ContactsCtrl">
<table border = "1";>
<tr><th>Email</a></th>
<th>Name</th></tr>
</table>
<div >
<table ng-repeat="Contact in ContactsCtrl.data.contactList" border="1">
<tr>
<td>{{Contact.Email}}</td>
<td>{{Contact.Name}}</td>
</tr>
</table>
</div>
<div>
<form>
<input type="input" ng-model="ContactsCtrl.data.contactList[currentContactID].Email"></input>
</form>
</div>
</div>
</body>
</html>
There are quite a few errors here such as :
ContactsCtrl has no information about the ContactList. You are trying to find object in array using ID in place in index using <table> element inside <div> and more..
Bascially, i have reduced the need of two controllers to one and made a Working Demo.

Route to AngularJS Page with :id parameter

I have an AngularJS Application which uses ngRoute to handle the routing of the app. The routing itself is working (the URL is being redirected to the correct page and the correct partial is open) however, I cannot retrieve the item which I need in the second page.
The first page lets you search for a list of documents (dummy at the moment but will eventually link to an API). The list items are clickable and will route you to the second page where the details of the document are listed.
I will outline the way I am attempting to achieve this at the moment but I am open to suggestions if anyone has ideas about how this solution can be improved.
app.js
angular.module("app", ["ngRoute", "ngAnimate"])
.config(function($routeProvider){
$routeProvider
.when("/main", {
templateUrl: "Views/main.html",
controller: "MainController"
})
.when("/document/:id", {
templateUrl: "Views/document.html",
controller: "DocumentController"
})
.otherwise({redirectTo: "/main"});
});
main.html
<link rel="stylesheet" href="Stylesheets/main.css" type="text/css">
<div id="docSearchPanel" class="col-xs-12">
<ng-include src="'Views/Partials/documentSearchForm.html'"></ng-include>
</div>
<div id="formSearchResultsArea">
<div id="documentsFoundHeader">Documents Found</div>
<div id="documentsTableContainer">
<table id="documentsTable" class="table">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="doc in documents" ng-click="showDocument()">
<td>{{doc.documentID}}</td>
<td>{{doc.documentTitle}}</td>
<td>{{doc.documentStatus}}</td>
</tr>
</tbody>
</table>
</div>
</div>
main.ctrl.js
angular.module("app").controller("MainController", function($scope, $location){
//This is populated by a function I have removed to keep the code simple
$scope.documents = []
$scope.showDocument = function(){
$scope.activeDocument = this.doc;
$location.path("document/"+this.doc.documentID);
};
});
document.html
<form ng-submit="downloadForm()" class="col-xs-12 col-md-6">
<h2>Document Details</h2>
<div class="row">
<h3>{{activeDocument.documentTitle}}</h3>
</div>
<div class="row" ng-repeat="field in selected.fields">
<div class="form-group">
<div class="document-attribute-header col-xs-5">{{field.key}}</div>
<div class="document-attribute-value col-xs-7">{{field.val}}</div>
</div>
</div>
</form>
document.ctrl.js
angular.module("app").controller("DocumentController", function($scope, $location, $routeParams){
$scope.activeDocument = getActiveDocument($routeParams.id);
function getActiveDocument(id){
for (var d in $scope.documents){
var doc = $scope.documents[d];
if (doc.documentID == id)
return doc;
}
}
});
The $scope-objects in the two controllers are not the same. You either make "documents" a member of the $rootScope (which you would need to inject in both controllers) or you make a documents-service which you inject.
Hope, that helped.

Get editable row of data from angular and sending it to WEB api

How do I send to the 'save' event the complete object including what ever the user has typed in that row? For now, those 2 fields are always NULL no matter what I do.
(the temp comment) Where do I put this? I want to get the item data when the 'save' is clicked but I if I put it in there how do I refer to the specific row?
The example I started with used separate pages for list/edit so the problem I am having is how to combine the functionality into one page.
var ListCtrl = function($scope, $location, Msa) {
$scope.items = Msa.query();
//temp: since I do not know how to get the value for specific row
var id = 1;
$scope.msa = Msa.get({id: id});
$scope.save = function() {
Msa.update({id: id}, $scope.msa, function() {
$location.path('/');
});
}
};
<tbody>
<tr ng-repeat="msa in items">
<td>{{msa.PlaceId}}</td>
<td>{{msa.Name}}</td>
<td>
<div class="controls">
<input type="text" ng-model="msa.PreviousPlaceId" id="PreviousPlaceId">
</div>
</td>
<td>
<div class="controls">
<input type="text" ng-model="msa.NextPlaceId" id="NextPlaceId">
</div>
</td>
<td>
<div class="form-actions">
<button ng-click="save()" class="btn btn-primary">
Update
</button><i class="icon-save"></i>
</div>
</td>
</tr>
</tbody>
It looks like it's in an ng-repeat so your scope isn't the same in the controller as in the ng-repeat.
I think you can just send in the current msa element from items and then in the save method, loop through the original list matching the element that's sent in and then update the fields.
<button ng-click="save(msa)" class="btn btn-primary">

Resources