Angularjs modal window with routeProvider - angularjs

I'm having trouble using routeProvider to display a modal window. I am displaying a table list of ingredients and hoping that by clicking on an ingredient, I can display an "update" modal. The table displays properly and I can even view a single ingredient outside of a modal context but as soon as I try and get the modal working everything falls apart - in fact, the modal doesn't even properly receive its "ingredient" variable. When clicking on a table row the HTML for the modal is displayed like it's a separate page.
app.js:
angular.module('IngredientsApp', [
'IngredientsApp.controllers',
'IngredientsApp.services',
'ngRoute',
'ui.bootstrap'
]).config(['$routeProvider', function($routeProvider) {
$routeProvider.
when("/ingredients", {templateUrl: "partials/ingredients.html", controller: "ingredientsController"}).
when("/ingredient/:id", {templateUrl: "partials/ingredient.html", controller: "ingredientController"}).
otherwise({redirectTo: '/ingredients'});
}]);
services.js:
angular.module('IngredientsApp.services', []).factory('ingredientAPIservice', function($http) {
var ingredientAPI = {};
ingredientAPI.getIngredients = function() {
return $http.get('/ingredient');
}
ingredientAPI.getIngredient = function(id) {
return $http.get('/ingredient/'+id+'/edit');
}
return ingredientAPI;
});
index.html
<!doctype html>
<html lang="en">
<head>
<title>Our Recipes</title>
<script type="text/javascript" src="/js/angular.min.js"></script>
<script type="text/javascript" src="/js/angular-route.min.js"></script>
<script type="text/javascript" src="/js/angular-bootstrap.min.js"></script>
<script type="text/javascript" src="/js/app.js"></script>
<script type="text/javascript" src="/js/services.js"></script>
<script type="text/javascript" src="/js/controllers.js"></script>
<link rel="stylesheet" type="text/css" href="/css/styles.css" />
</head>
<body ng-app="IngredientsApp">
<ng-view></ng-view>
</body>
</html>
ingredients.html
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Existing Ingredients</th>
<th><input type="text" ng-model="descriptionFilter" placeholder="Search..."/></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="i in ingredientsList | filter: searchFilter">
<td>
<a href="/#/ingredient/{{i.Id}}">
{{i.Description}}
</a>
</td>
<td>Created at {{i.CreatedAt}}</td>
</tr>
</tbody>
</table>
ingredient.html
<script type="text/ng-template">
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
{{ingredient.Description}}
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Dismiss</button>
</div>
</script>
controllers.js:
angular.module('IngredientsApp.controllers', []).controller('ingredientsController', function($scope, ingredientAPIservice) {
$scope.descriptionFilter = null;
$scope.ingredientsList = [];
$scope.searchFilter = function (ingredient) {
var keyword = new RegExp($scope.descriptionFilter, 'i');
return !$scope.descriptionFilter || keyword.test(ingredient.Description);
};
ingredientAPIservice.getIngredients().success(function (response) {
//Dig into the responde to get the relevant data
$scope.ingredientsList = response;
});
})
var ingredientController = function($scope, $routeParams, $modal, ingredientAPIservice) {
$scope.id = $routeParams.id;
$scope.ingredient = null;
ingredientAPIservice.getIngredient($scope.id).success(function (response) {
$scope.ingredient = response;
$scope.open = function (size) {
var modalInstance = $modal.open({
templateUrl: 'partials/ingredient.html',
controller: 'ingredientModalController',
size: size,
resolve: {
ingredient: function () {
console.log($scope.ingredient);
return $scope.ingredient;
}
}
});
}
});
}
var ingredientModalController = function($scope, $modalInstance, ingredient) {
$scope.ingredient = ingredient;
$scope.ok = function () {
$modalInstance.close($scope.ingredient);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}

I believe your issue is in app.js. Your route change causes the modal template (partials/ingredients.html) to be the only template displayed in ui-view. For the modal to work, you need to have the ingredients template nested within the ingredient template so both templates can be displayed at the same time. There are multiple ways to accomplish this.
If you are willing to give up the route change, just remove
when("/ingredient/:id", {templateUrl: "partials/ingredient.html", controller: "ingredientController"})
If you need the url to change, then I would look at doing it manually through the build in location service. https://docs.angularjs.org/guide/$location
You could just call a function that changes the url on click of an ingredient.

Related

Angular UI bootstrap modal is not working

I am new to angular and bootstrap. This is my Plunk.
This is my code of DemoController:
angular.module('app', ['ui.bootstrap'])
.controller('demoController', function($modal) {
this.message = 'It works!';
key = 1000;
this.modalInstance = this.modal = function(){
$modal.open({
controllerAs: 'modalController as modal',
templateUrl: 'modal.html',
resolve: {
key: function() {
return key;
}
}
});
};
this.modalInstance.result.then(function (optionSelected){
if(optionSelected == 'yes')
{
}
});
});
ModalController:
angular.module('app')
.controller('modalController', function($scope, $modalInstance, key) {
$scope.featureName = key;
$scope.yes = function () {
$modalInstance.close('yes');
};
$scope.discard = function () {
$modalInstance.close('discard');
};
$scope.goback = function () {
$modalInstance.close('goback');
};
});
Modal.html:
<script type="text/ng-template" id="modal.html">
<div class="modal-content">
<div class="modal-body">
<p>Do you want to save the changes to {{featureName}} </p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" ng-click="yes()">Yes</button>
<button type="button" class="btn btn-default" ng-click="discard()">Discrad</button>
<button type="button" class="btn btn-default" ng-click="goback()">Go Back</button>
</div>
</div>
</script>
Index.html:
<!DOCTYPE html>
<html>
<head>
<link data-require="bootstrap-css#3.1.1" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
<script data-require="angular.js#1.2.16" data-semver="1.2.16" src="https://code.angularjs.org/1.2.16/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.11.0/ui-bootstrap-tpls.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="app" ng-controller="demoController as demo">
<h1>{{ demo.message }}</h1>
<button class="btn btn-primary" ng-click="demo.modal()">Open modal</button>
</body>
</html>
I want to pass data from demo controller to modal controller. I want to have separate html and controller for the modal dialog. Somehow this is not working.
Here's a working plunker based on your own plunk: http://plnkr.co/edit/VDDyDuBoZ30tAk2kQKoc?p=preview
List of changed things:
In index.html, I added Ctrl.js to the list of loaded scripts.
In modal.html, removed the script tags surrounding the html. When loading the modal html from an external file, the script tags aren't necessary.
Finally in script.js made a few changes, ending up with the following:
angular.module('app', ['ui.bootstrap'])
.controller('demoController', function($modal) {
this.message = 'It works!';
var key = 1000;
this.modal = function() {
var modalInstance = $modal.open({
controller: 'modalController',
templateUrl: 'modal.html',
resolve: {
key: function() {
return key;
}
}
});
modalInstance.result.then(function(optionSelected) {
if (optionSelected === 'yes') {
console.log("Yes selected!")
}
})
}
});
Basically, this.modal is the function that's executed when clicking on the Open modal button. In the function, we initialize a variable modalInstance, which is the $modal.open function call. We also handle the modal result inside the this.modal function, not outside of it.
You have a lot of mistakes there. Here is your example:
plnkr.co/edit/47WJrWHW7ueYXBpiYJbA?p=preview

Issue with binding data from Modal Dialog to another area of web app

I've been searching around for a solution to a problem, which I believe should be relatively easy to solve - that being the use of Angular.js's two-way databinding
I have a modal dialog (using the Angular ui-bootstrap code for modal dialog) from which I want to take inputted text and output to the main application page, I've got a working Plunker (it works with data-binding as I can see the input value in the modal dialog), however i'm wanting to take that value and bind it to the section under Projects
my html
<!doctype html>
<html ng-app="ui.bootstrap.demo">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-animate.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.13.3.js"></script>
<script src="example.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title">Add Project</h3>
</div>
<div class="modal-body">
Project Name: <input type="text" ng-model="name"></input>
{{name}}
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
In Modal: {{ name }}
</script>
<button class="btn btn-default" ng-click="open()">Add Project</button>
</div>
<div class="col-lg-6">
<div class="table-responsive" ng-model="name">
<table class="table">
<thead>
<tr>
<th>Project</th>
<th>Badges</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{$scope.name}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
my javascript
angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl', function ($scope, $modal, $log) {
$scope.name = "";
$scope.open = function (size) {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
size: size,
resolve: {
projName: function () {
return $scope.name;
}
}
});
modalInstance.result.then(function (pName) {
$scope.name = pName;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
});
// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $modal service used above.
angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($scope, $modalInstance, projName) {
$scope.name = projName;
$scope.ok = function () {
$modalInstance.close($scope.name);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
Many Thanks in advance
As the main application page is operated by ModalDemoCtrl controller and model is operated by ModalInstanceCtrl controller, so they can't use the scope variable of each other, these controllers have no relationship.
There is the only way to pass ModalDemoCtrl scope variable data to ModalInstanceCtrl, using resolve method of $model service, as you did.
resolve:{items: function () {return $scope.items;}
and ModalInstanceCtrl scope data to ModalDemoCtrl using $modalInstance.close(modeldata), which you did.
so if you want to pass the modal input to main application. use it as below ...
In ModalInstanceCtrl
$scope.ok = function () {
$modalInstance.close($scope.name);
};
In ModalDemoCtrl
modalInstance.result.then(function (nameFromModal) {
$scope.name = nameFromModal;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});

How to do preloader for `ng-view` in Angular JS?

I use <div ng-view></div> on web page.
When I click link in block <div> is loaded HTML template was set in routeProvider. Also together is done request AJAX that returns data that was loaded template.
Now problem is that after click I get HTML template with empty form, still is working AJAX request. After some seconds form HTML is fiiled data from AJAX.
How I can do preloader to page for directory ng-view?
It seems that there are some similar questions here:
Angularjs loading screen on ajax request
Angular JS loading screen and page animation.
Also, there a bunch of modules to work with loading animation at http://ngmodules.org. For example, these:
https://github.com/cgross/angular-busy
https://github.com/chieffancypants/angular-loading-bar (I use this one in my apps)
https://github.com/McNull/angular-block-ui and other.
UPD:
I've written a simple solution based on how the angular-loading-bar works. I didn't test it with ng-view, but it seams to work with ui-view. It is not a final solution and have to be polished.
angular.module('ui')
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('LoadingListener');
}])
.factory('LoadingListener', [ '$q', '$rootScope', function($q, $rootScope) {
var reqsActive = 0;
function onResponse() {
reqsActive--;
if (reqsActive === 0) {
$rootScope.$broadcast('loading:completed');
}
}
return {
'request': function(config) {
if (reqsActive === 0) {
$rootScope.$broadcast('loading:started');
}
reqsActive++;
return config;
},
'response': function(response) {
if (!response || !response.config) {
return response;
}
onResponse();
return response;
},
'responseError': function(rejection) {
if (!rejection || !rejection.config) {
return $q.reject(rejection);
}
onResponse();
return $q.reject(rejection);
},
isLoadingActive : function() {
return reqsActive === 0;
}
};
}])
.directive('loadingListener', [ '$rootScope', 'LoadingListener', function($rootScope, LoadingListener) {
var tpl = '<div class="loading-indicator" style="position: absolute; height: 100%; width: 100%; background-color: #fff; z-index: 1000">Loading...</div>';
return {
restrict: 'CA',
link: function linkFn(scope, elem, attr) {
var indicator = angular.element(tpl);
elem.prepend(indicator);
elem.css('position', 'relative');
if (!LoadingListener.isLoadingActive()) {
indicator.css('display', 'none');
}
$rootScope.$on('loading:started', function () {
indicator.css('display', 'block');
});
$rootScope.$on('loading:completed', function () {
indicator.css('display', 'none');
});
}
};
}]);
It can be used like this:
<section class="content ui-view" loading-listener></section>
You can try something like this(simplest solution):
Set your loader animation/picture:<div class="loader" ng-show="isLoading"></div>
On div element add click event:
Then AJAX request success set isLoading=true
Download javascript and css files from PACE Loader.
Playing around with pace loader using ng-views . Hope this helps someone trying to use PACE.JS with Angular. In this example I am using ng-router to navigate between views.
app.js
var animateApp = angular.module('route-change-loader', ['ngRoute']);
var slowResolve = function(slowDataService){
return slowDataService.getContacts();
};
slowResolve.$inject = ['slowDataService'];
// ROUTING ===============================================
// set our routing for this application
// each route will pull in a different controller
animateApp.config(function($routeProvider) {
$routeProvider
// home page
.when('/route1', {
templateUrl: 'route1.html',
controller: 'slowCtrl',
controllerAs:'ctrl',
resolve: {
contacts:slowResolve
}
})
.otherwise({
templateUrl:'default.html'
});
});
var SlowCtrl = function(contacts) {
this.contacts = contacts;
};
SlowCtrl.$inject = ['contacts'];
angular.extend(SlowCtrl.prototype, {
message:'Look Mom, No Lag!',
contacts: []
});
animateApp.controller('slowCtrl', SlowCtrl);
var SlowDataService = function($timeout){
this.$timeout = $timeout;
};
SlowDataService.$inject = ['$timeout'];
angular.extend(SlowDataService.prototype, {
contacts:[{
name:'Todd Moto',
blog:'http://toddmotto.com/',
twitter:'#toddmotto'
},{
name:'Jeremy Likness',
blog:'http://csharperimage.jeremylikness.com/',
twitter:'#jeremylikness'
},{
name:'John Papa',
blog:'http://www.johnpapa.net/',
twitter:'#John_Papa'
},{
name:'Josh Carroll',
blog:'http://www.technofattie.com/',
twitter:'#jwcarroll'
}],
getContacts:function(){
var _this = this;
return this.$timeout(function(){
return angular.copy(_this.contacts);
}, 1000);
}
});
animateApp.service('slowDataService', SlowDataService);
index.html
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Test Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" href="pace.css">
<script src="http://code.angularjs.org/1.2.13/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular-route.js"></script>
<script src="app.js"></script>
<script src="pace.js"></script>
</head>
<body ng-app="route-change-loader">
<div class="container">
<div class="masthead">
<ul class="nav nav-tabs">
<li>
Default
</li>
<li>
Slow Loading Controller
</li>
</ul>
</div>
<!-- Jumbotron -->
<div class="row">
<route-loading-indicator></route-loading-indicator>
<div ng-if="!isRouteLoading" class="col-lg-12" ng-view=""></div>
</div>
<!-- Site footer -->
<div class="footer">
<p>by <b>Ritesh Karwa</b> </a>
</p>
</div>
</div>
</body>
</html>
default.html
<h1>Click on the tabs to change routes</h1>
route1.html
<h1>{{ctrl.message}}</h1>
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Blog</th>
<th>Twitter</th>
</tr>
</thead>
<tbody>
<tr ng-repeat='contact in ctrl.contacts'>
<td>{{contact.name}}</td>
<td>{{contact.blog}}</td>
<td>{{contact.twitter}}</td>
</tr>
</tbody>
</table>

How to filter out a user using ng-repeat within firebase and angularfire?

The below code pulls an array from firebase using ng-repeat and filters for the userId.
The issue is that when I use "!" it does not filter out the user, but instead nothing shows up. In other words when I replace the below ng-repeat filter:
ng-repeat="(id,item) in ideas| filter:user.google.id"
with this ng-repeat filter, with the intention of filtering out the user, it no longer works.
ng-repeat="(id,item) in ideas| filter:user.google.id"
How can I filter out list for any item that contains the user id?
See below and in this codepen for the full code: http://codepen.io/chriscruz/pen/LERrBW
HTML
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<script src="https://cdn.firebase.com/js/client/2.0.2/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/0.9.0/angularfire.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" type="text/css">
</head>
<body ng-controller="ctrl">
<p>Welcome, {{user.google.displayName}}</p>
<button class="btn btn-lg btn-danger" id="Gbtn" ng-click="GoogleLogin()">
<i class="fa fa-google-plus-square fa-2x"></i>
Login with Google</button>
<table>
<tr class="item" ng-repeat="(id,item) in ideas| filter:user.google.id">
<td>{{item.idea}}</td>
</tr>
</table>
</body>
</html>
Javascript:
var app = angular.module("app", ["firebase"]);
app.constant("FBURL", "https://crowdfluttr.firebaseio.com/");
app.service("Ref", ["FBURL", Firebase]);
app.factory("Auth", ["$firebaseAuth", "Ref", function($firebaseAuth, Ref) {
return $firebaseAuth(Ref);
}]);
app.factory("Ideas", ["$firebase", "Ref", function($firebase, Ref) {
var childRef = Ref.child('ideas');
var lst = $firebase(childRef).$asArray();
return lst
}]);
app.controller("ctrl", ["$scope","$firebase","Ideas","Auth", function($scope,$firebase,Ideas,Auth) {
$scope.ideas = Ideas;
$scope.auth = Auth;
$scope.idea = "";
$scope.GoogleLogin = function () {
$scope.auth.$authWithOAuthPopup('google')()
};
}]);
app.run(["$rootScope", "Auth", function($rootScope, Auth) {
$rootScope.user = Auth.$getAuth();
}]);

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