ng-repeat not binding from database - angularjs

I have a 1 page application which should display a list of objects from a database. I used ng-repeat to create a template to bind data from array in db. As I am new to Angular any help would be great. My code is below:
SERVER.JS
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('eventlist', ['eventlist']);
var bodyParser = require('body-parser');
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
app.get('/eventlist', function (req, res) {
console.log("i received a get request")
db.eventlist.find(function(err, docs){
console.log(docs);
res.json(docs);
});
});
app.post('/eventlist', function (req, res){
console.log(req.body);
db.eventlist.insert(req.body, function (err, doc) {
res.json(doc);
});
});
app.delete('/eventlist/:id', function(req, res){
var id = req.params.id;
console.log(id);
db.eventlist.remove({_id: mongojs.ObjectID(id)}, function (err, doc) {
res.json(doc);
});
});
app.get('/eventlist/:id', function (req, res) {
var id = req.params.id;
console.log(id);
db.eventlist.findOne({_id: mongojs.ObjectId(id)}, function (err, doc) {
res.json(doc);
});
});
app.put('/eventlist/:id', function (req, res) {
var id = req.params.id;
console.log(req.body.name);
db.eventlist.findAndModify({
query: {_id: mongojs.ObjectId(id)},
update: {$set: {name: req.body.name, startDate: req.body.startDate, price: req.body.price, location: req.body.location}},
new: true}, function (err, doc) {
res.json(doc);
}
);
});
app.listen(4000);
console.log("Server running on port 4000");
INDEX.HTML
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="css/page.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">
<title>Capstone Project</title>
<meta name="description" content="Carnival and Event Mapping tool">
<link rel="manifest" href="/manifest.json">
</head>
<body>
<div id="wrapper">
<div class="overlay"></div>
<!-- Sidebar -->
<nav class="navbar navbar-inverse navbar-fixed-top" id="sidebar-wrapper" role="navigation">
<ul class="nav sidebar-nav">
<li class="sidebar-brand">
<a href="#">
Brand
</a>
</li>
<li>
Enter Zip Code
</li>
<li>
<input type="text"/><button>Submit</button>
</li>
<li class="dropdown">
Events Near Me<span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li class="dropdown-header">Select Radius</li>
<li>5 Miles</li>
<li>10 Miles</li>
<li>15 Miles</li>
</ul>
</li>
<li>
Ascending
</li>
<li>
Descending
</li>
<li>
Contact
</li>
</ul>
</nav>
<!-- /#sidebar-wrapper -->
<!-- Page Content -->
<div id="page-content-wrapper">
<button type="button" class="hamburger is-closed" data-toggle="offcanvas">
<span class="hamb-top"></span>
<span class="hamb-middle"></span>
<span class="hamb-bottom"></span>
</button>
<div class="container" ng-controller="AppCtrl">
<h1>Summer Event List</h1>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Date</th>
<th>Price</th>
<th>Location</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><input class="form-control" ng-model="event.name"></td>
<td><input class="form-control" ng-model="event.startDate"></td> <!--type="date" (put this next to startDate)-->
<td><input class="form-control" ng-model="event.price"></td> <!--$<input type="number" name="currency" min="0" max="9999" step="0.01" size="4"
title="CDA Currency Format - no dollar sign and no comma(s) - cents (.##) are optional" />-->
<td><input class="form-control" ng-model="event.location"></td>
<td><button class="btn btn-primary" ng-click="addEvent()">Add Event</button></td>
<td><button class="btn btn-primary" ng-click="deselect()">Clear</button></td>
</tr>
<tr ng-repeat="event in eventlist"> <!--also tried ng-repeat="event in eventlist track by $indexs"-->
<td>{{event.name}}</td>
<td>{{event.startDate}}</td>
<td>{{event.price}}</td>
<td>{{event.location}}</td>
<!-- <td><button class="btn btn-danger" ng-click="remove(contact._id)">Remove</button></td>
<td><button class="btn btn-warning" ng-click="edit(contact._id)">Edit</button></td> -->
</tr>
</tbody>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js" charset="utf-8"></script>
<script src="controllers/controller.js" charset="utf-8"></script>
</body>
</html>
</div>
<!-- /#page-content-wrapper -->
<script>
$(document).ready(function () {
var trigger = $('.hamburger'),
overlay = $('.overlay'),
isClosed = false;
trigger.click(function () {
hamburger_cross();
});
function hamburger_cross() {
if (isClosed == true) {
overlay.hide();
trigger.removeClass('is-open');
trigger.addClass('is-closed');
isClosed = false;
} else {
overlay.show();
trigger.removeClass('is-closed');
trigger.addClass('is-open');
isClosed = true;
}
}
$('[data-toggle="offcanvas"]').click(function () {
$('#wrapper').toggleClass('toggled');
});
});
</script>
</body>
</html>
CONTROLLER.JS
var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', '$http', function($scope, $http) {
console.log("Hello World from controller");
var refresh = function(){
$http.get('/eventlist/').then(function(response) {
console.log("I got the data I requested");
$scope.eventlist = response;
$scope.event = null;
});
};
refresh();
$scope.addEvent = function () {
console.log($scope.event);
$http.post('/eventlist/', $scope.event).then(function(response){
console.log(response);
refresh();
});
$scope.update = function() {
console.log($scope.event._id);
$http.put('/eventlist/' + $scope.event._id, $scope.event).then(function(response) {
refresh();
})
};
};
$scope.remove = function(id) {
console.log(id);
$http.delete('/eventlist/' + id).then(function(response) {
refresh();
});
};
$scope.edit = function(id) {
console.log(id);
$http.get('/eventlist/' + id).then(function(response) {
$scope.event = response;
});
};
$scope.deselect = function() {
$scope.event = null;
refresh();
};
}]);

Change it as response.data,
var refresh = function(){
$http.get('/eventlist/').then(function(response) {
$scope.eventlist = response.data;
$scope.event = null;
});
};

Related

$http.delete returns error 404

I am new to Angular and I'm trying to build a CRUD using the MEAN stack.
Yet I am having trouble with Angular to call the DELETE function on the server side.
Here is my Angular App.JS
var app = angular.module('topshelf', [])
app.controller('MainCtrl', [
'$scope','$http',
function($scope , $http){
var Mydata = {};
$http.get("http://localhost:8080/inventory").success(function(data,status,header,config){
$scope.Mydata = data;
});
$scope.delete = function($index) {
var url = "http://localhost:8080/ingredients/" + $index;
$http.delete(url).success(function(err,data){
if (err){ console.log(err);}
$scope.Mydata = data;
console.log("test");
});
}
}]);
and here is my HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TopShelf</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="font-awesome/css/font-awesome.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
<script src="./app.js"></script>
</head>
<body ng-app ="topshelf" ng-controller="MainCtrl" class="top-navigation">
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>Ingredient</th>
<th>Quantity</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="ingredients in Mydata">
<td>{{ingredients.name}} </td>
<td>{{ingredients.quantity}} </td>
<td> Add / Edit / <a ng-click="delete($index)">Delete</a></form></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
UPDATE
Also, here is my server code specifying the routes though when I try the routes with POSTMAN it works fine.:
var express = require('express');
var Ingredients = require('./models/ingredients.js');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
mongoose.connect('mongodb://localhost/labelleassiette');
app.use(bodyParser.urlencoded({extended: true}))
app.use(express.static(__dirname + '/public'));
app.get('/', function(req,res){
res.sendFile(__dirname+"/public/index.html");
})
app.get('/inventory',function(req,res){
Ingredients.find(function(err,ingr){
res.json(ingr);
})
})
app.post('/add', function(req,res){
var entry = new Ingredients({name: req.body.name, quantity: req.body.quantity});
var self = this;
Ingredients.find({name:req.body.name}, function(err,data){
if(data.length){
res.send(500,"Ingredient exists!");
}
else{
entry.save(function(err){
if (err) {console.log(err);}
else { console.log('Saved to db')}
});
res.redirect('/');
}
})
})
app.put('/ingredients/:id',function(req,res) {
var id = req.params.id;
var obj = req.body;
Ingredients.findByIdAndUpdate(id, {name: obj.name, quantity: obj.quantity}, function(err){
if (err) {console.log(err);}
console.log("updated");
})
})
app.delete('/ingredients/:id',function(req,res){
Ingredients.findByIdAndRemove(req.params.id,function(err){
if (err) {console.log(err);}
console.log("effacé");
res.redirect('/');
})
})
app.listen(8080, function() {
console.log("listening on port 8080!");
});
i am getting a DELETE http://localhost:8080 404 not found on my browser's console.
Thank you guys for your help

Get autocompleted value from input in controller

I have the following in my view:
<label for="txtFrom">Pickup Location</label>
<input type="text" id="pickup" placeholder="Address, aiport, train station, hotel..." ng-model="pickup">
<label for="txtDestination">Destination</label>
<input type="text" id="destination" placeholder="Address, aiport, train station, hotel..." ng-model="destination">
<input class="btn btn-success" name="calcPrice" id="calcPrice" type="submit" value="Calculate Price" ng-click="calcPrice()">
I am using google maps api for places to autocomplete the input boxes, so if a user starts typing "Lo", he will get a list of places that starts with "Lo" and for example he chooses London.
The problem is in my controller I am not getting the whole autocompleted value. I am only getting what the user initially entered, in this case "Lo".
Here is my controller:
app.controller('BookingsCtrl', function($scope, BookingsService) {
$scope.pickup = "";
$scope.destination = "";
$scope.syncNotification = "";
$scope.calcPrice = function() {
console.log($scope.pickup);
BookingsService.save({
pickup: $scope.pickup,
destination: $scope.destination
}, function(response) {
console.log(response.message);
});
};
});
EDIT:
Here is also a snippet of the JS:
var pickup = document.getElementById('pickup');
var options = {
componentRestrictions: {
country: 'ee'
}
};
var autocompletePickup = new google.maps.places.Autocomplete(pickup, options);
google.maps.event.addListener(autocompletePickup, 'place_changed', function () {
var place = autocompletePickup.getPlace();
pickup.innerHtml = place.formatted_address;
var lat = place.geometry.location.lat();
var long = place.geometry.location.lng();
});
EDIT 2 : Added service
app.service('BookingsService', function ($resource) {
return $resource('http://localhost:3000/', {});
});
EDIT 3 : Template
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="components/bootstrap/dist/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="assets/css/style.css" type="text/css" />
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDt1Y30OssBToIzSCOr3g5IkN3c0D75XVE&libraries=places"
></script>
</head>
<body ng-app='strelsau_client'>
<div class="site-wrapper">
<div class="site-wrapper-inner">
<div class="cover-container">
<div class="masthead clearfix">
<div class="inner">
<img class="masthead-brand" src="../assets/img/logo.png">
<nav>
<ul class="nav masthead-nav">
<li class="active">Home</li>
<li>Contact</li>
</ul>
</nav>
</div>
</div>
<div ng-view>
</div>
</div>
</div>
</div>
<script src="components/jquery/dist/jquery.min.js"></script>
<script src="components/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="components/angular/angular.min.js"></script>
<script src="components/angular-route/angular-route.min.js"></script>
<script src="components/angular-resource/angular-resource.min.js"></script>
<script src="js/main.js"></script>
<script src="js/controllers/bookings_controllers.js"></script>
<script src="js/services/bookings_service.js"></script>
</body>
</html>
In fact pickup input element is not getting updated once the place is resolved.
The problem with this function:
google.maps.event.addListener(autocompletePickup, 'place_changed', function () {
var place = autocompletePickup.getPlace();
pickup.innerHtml = place.formatted_address; //invalid
//...
});
For setting input field value should be used value property.
Anyway, given the example, try to replace it with:
(function (scope) {
google.maps.event.addListener(autocompletePickup, 'place_changed', function () {
var place = autocompletePickup.getPlace();
scope.pickup = place.formatted_address;
});
})($scope);
Example
angular.module('myApp', [])
.controller('BookingsCtrl', function ($scope) {
$scope.pickup = "";
$scope.destination = "";
$scope.syncNotification = "";
var pickup = document.getElementById('pickup');
var options = {
componentRestrictions: {
country: 'ee'
}
};
var autocompletePickup = new google.maps.places.Autocomplete(pickup, options);
(function (scope) {
google.maps.event.addListener(autocompletePickup, 'place_changed', function () {
var place = autocompletePickup.getPlace();
scope.pickup = place.formatted_address;
});
})($scope);
$scope.calcPrice = function () {
console.log($scope.pickup);
alert($scope.pickup);
/*BookingsService.save({
pickup: $scope.pickup,
destination: $scope.destination
}, function (response) {
console.log(response.message);
});*/
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div ng-app="myApp" ng-controller="BookingsCtrl" ng-cloak>
<label for="txtFrom">Pickup Location</label>
<input type="text" id="pickup" placeholder="Address, aiport, train station, hotel..." ng-model="pickup">
<label for="txtDestination">Destination</label>
<input type="text" id="destination" placeholder="Address, aiport, train station, hotel..." ng-model="destination">
<input class="btn btn-success" name="calcPrice" id="calcPrice" type="submit" value="Calculate Price" ng-click="calcPrice()">
</div>

AngularJS POST and GET 404 Error

Using AngularJS, I'm trying to post data from a form into an ng-repeat and save to a database. When I click submit, I get the 404 error for post and get. Can someone help show me where I went wrong?
Here's my html:
<html ng-app="Inventory-App">
<head>
<meta charset="utf-8">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.js" charset="utf-8"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<!-- SEMANTIC -->
<link rel="stylesheet" type="text/css" href="../semantic/dist/semantic.min.css">
<script src="../semantic/dist/semantic.min.js"></script>
<!-- MY STUFF -->
<link rel="stylesheet" href="../css/styles.css" media="screen" title="no title" charset="utf-8">
<script src="../scripts/script.js" charset="utf-8"></script>
<script src="../scripts/services/itemsAPI.js" charset="utf-8"></script>
<script src="../scripts/controllers/main.js" charset="utf-8"></script>
<script src="../scripts/app.js" charset="utf-8"></script>
</head>
<body ng-controller="MainController">
<nav>
<h1>Cabinet.me</h1>
<p>An Inventory of Your Kitchen</p>
</nav>
<div class="ui container">
<form class="ui form">
<div class="field">
<label>Item</label>
<input type="text" placeholder="Item" ng-model="post.name">
</div>
<div class="field">
<label>Details (if any)</label>
<input type="text" placeholder="Details" ng-model="post.details">
</div>
<div class="field">
<label>Amount</label>
<select class="ui dropdown" ng-model="post.amount">
<option value="">Amount</option>
<option value="1">High</option>
<option value="1">Medium</option>
<option value="0">Low</option>
</select>
</div>
<button class="ui button" type="submit" ng-click="createItem(post)">Submit</button>
</form>
<div class="ui divider"></div>
<div class="ui cards">
<div class="card" ng-repeat="item in items | orderBy: 'created_at':true">
<div class="content">
<div class="header">{{item.name}}</div>
<div class="meta">Availability: {{item.amount}}</div>
<div class="description">
{{item.details}}
</div>
<button class="ui secondary button">
Delete
</button>
</div>
</div>
</div>
</div>
</body>
</html>
Here's my Controller:
angular
.module('mainController', ['itemsAPI'])
.controller('MainController', ['$scope', '$http', 'itemsAPI',
function( $scope, $http, itemsAPI ) {
$scope.items = [];
// $scope.itemData = '';
$scope.createItem = function(post){
var newItem = {
item : {
name: post.name,
details: post.details,
amount: post.amount
}
}
itemsAPI.create(newItem).then(function(response){
console.log(response);
$scope.items.push(response.data);
})
itemsAPI.getAll().then(function(response){
$scope.items = response.data;
});
}
$scope.removeItem = function(item){
itemsAPI.remove(item._id).then(function(response){
if (response.status == 203) {
$scope.items = $scope.items.filter(function(i){
return i._id != item._id;
});
}
});
}
}]);
Here's the itemsAPI code:
angular
.module('itemsAPI', [])
.factory('itemsAPI', ['$http',
function($http) {
return {
getAll: function(){
return $http.get('/items');
},
create: function(newItem){
return $http.post('/items', newItem);
},
remove: function(id){
return $http.delete('/items/' + id);
}
}
}])
And my API route:
var express = require('express');
var router = express.Router();
var Item = require('../../models/item');
// Get
router.get('/', function(req, res, next) {
Item.find(function(err, items) {
if (err) {
next(err);
}else {
res.json(items);
}
})
});
router.post('/', function(req, res, next) {
Item.create(req.body.item, function(err, item) {
if (err) {
next(err);
}else {
res.json(item);
}
});
});
router.delete('/:id', function(req, res, next) {
Item.findByIdAndRemove(req.params.id, function(err) {
if (err) {
next(err);
}else {
res.status(203).end();
}
})
});
module.exports = router;
I appreciate any help I can get!
Replace this
router.post('/', function(req, res){
with
router.post('/items', function(req, res){
in inventory/server/routes/api/items.js
Edit:
I'm mistaken. You use '/api/items' route in app.js and not necessary to add 'items' path as I wrote above. But on the client side you try to post your data on the '/items' route not on '/api/items'.

How to get the insert page to show success, when data is entered with MEAN App

I have been trying to figure how to make my MEAN APP to show a message saying Data Successfully entered! I am not sue how to go about this I am new to MEAN and still learning.
insert.html
<!DOCTYPE>
<html ng-app="myApp">
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<title>Contact list app</title>
</head>
<body>
<div class="container" ng-controller="AppCtrl">
<h1>Contact List App</h1>
<table class="table">
<div class="row">
<div class="form-group col-xs-5 col-lg-4">
<label for="name">Name</label>
<input type="text" class="form-control " ng-model="contact.name"/>
</div>
</div>
<div class="row">
<div class="form-group col-xs-5 col-lg-4 ">
<label for="email">Email</label>
<input type="text" class="form-control " ng-model="contact.email"/>
</div>
</div>
<div class="row">
<div class="form-group col-xs-5 col-lg-4 ">
<label for="number">Number</label>
<input type="text" class="form-control "ng-model="contact.number" />
</div>
</div>
<br>
<div class="row">
<button type="submit" class="btn btn-default" ng-click="addContact()">Add Contact</button>
</div>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="controllers/controller.js"></script>
</body>
</html>
controller.js
var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', '$http', function($scope, $http) {
console.log("Hello World from controller");
var refresh= function(){
$http.get('/contactlist').success(function(response) {
console.log("I got the data I requested");
$scope.contactlist = response;
$scope.contact = "";
});
};
refresh();
$scope.addContact = function(){
console.log($scope.contact);
$http.post('/contactlist', $scope.contact).success(function(response){
console.log(response);
refresh();
});
};
$scope.remove = function(id){
console.log(id);
$http.delete('/contactlist/' + id).success(function(response){
refresh();
});
};
$scope.edit = function(id) {
console.log(id);
$http.get('/contactlist/' + id).success(function(response) {
$scope.contact = response;
});
};
}]);
server.js
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('contactlist', ['contactlist']);
var bodyParser = require('body-parser');
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());
app.get('/contactlist', function (req, res){
console.log("I received a Get request")
db.contactlist.find(function(err, docs){
console.log(docs);
res.json(docs);
});
});
app.post('/contactlist', function(req, res){
console.log(req.body);
db.contactlist.insert(req.body, function(err, doc){
res.json(doc);
});
});
app.delete('/contactlist/:id', function(req, res){
var id= req.params.id;
console.log(id);
db.contactlist.remove({_id: mongojs.ObjectId(id)}, function (err, doc){
res.json(doc);
})
});
app.get('/contactlist/:id', function (req, res) {
var id = req.params.id;
console.log(id);
db.contactlist.findOne({_id: mongojs.ObjectId(id)}, function (err, doc) {
res.json(doc);
});
});
app.listen(3000);
console.log("server running on port 3000");
After the post request is completed, you can show a message:
$scope.addContact = function() {
$http.post('/contactlist', $scope.contact).success(function(response) {
alert(response);
alert("Data Inserted");
refresh();
});
};

angular js not waiting for rest response

I am new to angular js. I have to work with the rest calls in java. I have taken an example related to angularjs, java rest.
see app.js
angular.module('ngdemo', ['ngRoute','ngdemo.filters', 'ngdemo.services', 'ngdemo.directives', 'ngdemo.controllers']).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/user-list', {templateUrl: 'partials/user-list.html', controller: 'UserListCtrl'});
$routeProvider.when('/user-detail/:id', {templateUrl: 'partials/user-detail.html', controller: 'UserDetailCtrl'});
$routeProvider.when('/user-creation', {templateUrl: 'partials/user-creation.html', controller: 'UserCreationCtrl'});
}]);
controllers.js
'use strict';
/* Controllers */
var app = angular.module('ngdemo.controllers', []);
app.run(function ($rootScope, $templateCache) {
$rootScope.$on('$viewContentLoaded', function () {
$templateCache.removeAll();
});
});
app.controller('UserListCtrl', ['$scope', 'UsersFactory', 'UserFactory', 'DeleteUserFactory', 'UsersSearchFactory', '$location',
function ($scope, UsersFactory, UserFactory, DeleteUserFactory, UsersSearchFactory, $location) {
// callback for ng-click 'editUser':
$scope.editUser = function (userId) {
$location.path('/user-detail/' + userId);
};
$scope.searchUser = function () {
$scope.users = UsersSearchFactory.search($scope.user);
};
// callback for ng-click 'deleteUser':
$scope.deleteUser = function (user) {
DeleteUserFactory.delete(user);
$scope.users = UsersFactory.query({startRow: 0}, {endRow: 75});
};
// callback for ng-click 'createUser':
$scope.createNewUser = function () {
$location.path('/user-creation');
};
$scope.users = UsersFactory.query({startRow: 0}, {endRow: 75});
}]);
app.controller('UserDetailCtrl', ['$scope', '$routeParams', 'UserFactory', 'UpdateUserFactory', '$location',
function ($scope, $routeParams, UserFactory, UpdateUserFactory, $location) {
// callback for ng-click 'updateUser':
$scope.updateUser = function () {
UpdateUserFactory.update($scope.user);
$location.path('/user-list');
};
// callback for ng-click 'cancel':
$scope.cancel = function () {
$location.path('/user-list');
};
$scope.user = UserFactory.show({id: $routeParams.id});
}]);
app.controller('UserCreationCtrl', ['$scope', 'CreateUserFactory', '$location',
function ($scope, CreateUserFactory, $location) {
// callback for ng-click 'createNewUser':
$scope.createNewUser = function () {
CreateUserFactory.create($scope.user);
$location.path('/user-list');
}
}]);
services.js
'use strict';
/* Services */
var services = angular.module('ngdemo.services', ['ngResource']);
services.factory('UsersFactory', function ($resource) {
return $resource('/ngdemo/rest/getUsers/:startRow/:endRow', {}, {
query: { method: 'GET', isArray: true, params: {startRow: '#startRow', endRow: '#endRow'} },
create: { method: 'POST' }
})
});
services.factory('UsersCountFactory', function ($resource) {
return $resource('/ngdemo/rest/getUsersCount', {}, {
count: { method: 'GET'}
})
});
services.factory('UsersSearchFactory', function ($resource) {
return $resource('/ngdemo/rest/searchUser', {}, {
search: { method: 'POST', isArray: true, }
})
});
services.factory('CreateUserFactory', function ($resource) {
return $resource('/ngdemo/rest/registerUser', {}, {
create: { method: 'POST' }
})
});
services.factory('UpdateUserFactory', function ($resource) {
return $resource('/ngdemo/rest/updateUser', {}, {
update: { method: 'POST' }
})
});
services.factory('DeleteUserFactory', function ($resource) {
return $resource('/ngdemo/rest/deleteUser', {}, {
delete: { method: 'POST' }
})
});
services.factory('UserFactory', function ($resource) {
return $resource('/ngdemo/rest/findUserById/:id', {}, {
show: { method: 'GET' }
})
});
user-list.html
<div class="container">
<form novalidate="novalidate" class="form-horizontal">
<div class="control-group">
<label class="control-label" for="inputFirstName">First name:</label>
<div class="controls">
<input type="text" id="inputFirstName" ng-model="user.firstName" placeholder="First name"/>
</div>
</div>
<div class="form-group">
<div class="controls">
<a ng-click="searchUser()" class="btn btn-primary btn-xs">Search</a>
</div>
</div>
</form>
</div>
<div class="span6">
<table class="table table-striped table-condensed" >
<thead>
<tr>
<th style="min-width: 80px;"> First Name</th>
<th style="min-width: 80px;"> Last Name</th>
<th style="width:20px;"> </th>
<th style="width:20px;"> </th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users" > <!-- | orderBy:sort.sortingOrder:sort.reverse" > -->
<td>{{ user.firstName }}</td>
<td>{{ user.lastName }}</td>
<td><a ng-click="editUser(user.userId)" class="btn btn-small btn-primary">edit</a></td>
<td><a ng-click="deleteUser(user)" class="btn btn-small btn-danger">delete</a></td>
</tr>
</tbody>
</table>
<a ng-click="createNewUser()" class="btn btn-small">create new user</a>
</div>
index.html
<!doctype html>
<html lang="en" ng-app="ngdemo">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ngdemo app</title>
<link rel="stylesheet" href="css/app.css"/>
<link rel="stylesheet" href="css/bootstrap/bootstrap-responsive.min.css"/>
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css"/>
</head>
<body>
<ul class="menu">
<li>user-list</li>
</ul>
<div ng-view></div>
<!-- JQuery ================================================================ -->
<script src="js/jquery/jquery-2.0.3.js"></script>
<!-- Bootstrap ============================================================= -->
<script src="js/bootstrap/bootstrap.js"></script>
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-resource.js"></script>
<script src="lib/angular/angular-route.js"></script>
<!-- AngularJS App Code ==================================================== -->
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
<script src="js/directives.js"></script>
</body>
</html>
Question:
I am getting the rest call to server and it is sending the response.
When i open index.html it is displaying the out put on the page. When i click on edit(update) or delete buttons or create new user button, the user details are saved in the database but the changed data is not displayed on the table.
This is happened because after editing(updating) , deleting and creating new user the angular code is not waiting for the response from REST call. It immediately calls the $location.path('/user-list'); So old data is displayed in the table.
Please help me.
I have added the success call backs for all the methods update, create, delete as
$scope.createNewUser = function () {
CreateUserFactory.create($scope.user, function(response) {
$location.path('/user-list');
});
}

Resources