Factory not providing proper values to controller - angularjs

In my angular js project factory is not providing values to the controller as needed. I always get empty result in view. When i logged in browser using console.log() all i can see in console is :
[object Object],[object Object],[object Object]. I am stuck at this. Tried many things but nothing worked.
This is my controller code:
var controllers = {};
controllers.ProductController = function ($scope, $route, $routeParams, $location, ProductFactory) {
$scope.products = [];
var init = function () {
$scope.products = ProductFactory.getProducts();
console.log('got products in controller');
console.log($scope.products)
};
var initProductEdit = function () {
var code = $routeParams.code;
if (code = undefined) {
$scope.currentProduct = {};
}
else
{
$scope.currentProduct = ProductFactory.loadProductByCode(code);
}
};
$scope.$on('$viewContentLoaded', function () {
var templateUrl = $route.current.templateUrl;
if (templateUrl == '/Partials/ProductEdit.html') {
initProductEdit();
}
else if (templateUrl == '/Partials/ProductList.html')
{
var code = $routeParams.code;
if(code!=undefined)
{
$scope.deleteProduct(code);
}
}
});
init();
$scope.saveProduct = function () {
ProductFactory.saveProduct($scope.currentProduct);
$location.search('code', null);
$location.path('/');
};
$scope.deleteProduct = function (code) {
ProductFactory.deleteProduct(code);
$location.search('code', null);
$location.path('/');
};
};
angSPA.controller(controllers);
This is my factory code:
angSPA.factory('ProductFactory', function () {
var products = [
{ code: 1, name: 'Game of Thrones', description: 'Series' }
{ code: 2, name: 'DmC', description: 'Game' },
{ code: 3, name: 'Matrix', description: 'Movie' },
{ code: 4, name: 'Linkin Park', description: 'Music Band' }];
var factory = {};
console.log('initializing factory');
factory.getProducts = function () {
console.log('factory now providing products');
return products;
};
factory.loadProductByCode = function (code) {
var product;
for (var i = 0; i < products.length; i++) {
if (products[i].code == code) {
product = products[i];
return product;
}
}
};
factory.saveProduct = function (product) {
products.push(product);
console.log('factory saved product');
};
factory.deleteProduct = function (code) {
var product = factory.loadProductByCode(code);
if (product != null) {
products.remove(product);
console.log('factory deleted product');
}
};
console.log('returning factory');
return factory;
});
This is my view:
<div class="container">
<h2 class="page-title">Product Listing</h2>
<div class="searchbar">
<ul class="entity-tabular-fields">
<li>
<label>Search: </label>
<span class="field-control">
<input type="text" data-ng-model="filter.productName" />
</span>
<label></label>
</li>
</ul>
</div>
<h2>Add New Product</h2>
<table class="items-listing">
<thead>
<tr>
<th>Code</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td data-ng-repeat="product in products|filter:filter.productName"></td>
<td>{{product.code}}</td>
<td>{{product.name}}</td>
<td>{{product.description}}</td>
<td>Delete</td>
</tr>
</tbody>
</table>
</div>
My routing function:
angSPA.config(function ($routeProvider) {
$routeProvider
.when(
'/',
{
controller: 'ProductController',
templateUrl: 'Partials/ProductList.html'
})
.when(
'/ProductEdit',
{
controller: 'ProductController',
templateUrl: 'Partials/ProductEdit.html'
})
.otherwise({
redirectTo: '/'
});
console.log('routing done');
});

Change your htmt given
var angSPA = angular.module('angSPA', []);
angSPA.controller("ProductController", function($scope, ProductFactory) {
$scope.products = [];
var init = function() {
$scope.products = ProductFactory.getProducts();
console.log('got products in controller');
console.log($scope.products + "")
};
init();
});
angSPA.factory('ProductFactory', function() {
var products = [
{code: 1, name: 'Game of Thrones', description: 'Series'},
{code: 2, name: 'DmC', description: 'Game'},
{code: 3, name: 'Matrix', description: 'Movie'},
{code: 4, name: 'Linkin Park', description: 'Music Band'}];
var factory = {};
console.log('initializing factory');
factory.getProducts = function() {
console.log('factory now providing products');
return products;
};
factory.loadProductByCode = function(code) {
var product;
for (var i = 0; i < products.length; i++) {
if (products[i].code == code) {
product = products[i];
return product;
}
}
};
factory.saveProduct = function(product) {
products.push(product);
console.log('factory saved product');
};
factory.deleteProduct = function(code) {
var product = factory.loadProductByCode(code);
if (product != null) {
products.remove(product);
console.log('factory deleted product');
}
};
console.log('returning factory');
return factory;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<body ng-app="angSPA" ng-controller="ProductController">
<div class="container">
<h2 class="page-title">Product Listing</h2>
<div class="searchbar">
<ul class="entity-tabular-fields">
<li>
<label>Search: </label>
<span class="field-control">
<input type="text" data-ng-model="filter.productName" />
</span>
<label></label>
</li>
</ul>
</div>
<h2>Add New Product</h2>
<table class="items-listing">
<thead>
<tr>
<th>Code</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="prod in products|filter:filter.productName">
<td ></td>
<td>{{prod.code}}</td>
<td>{{prod.name}}</td>
<td>{{prod.description}}</td>
<td>Delete</td>
</tr>
</tbody>
</table>
</div>

Your ng-repeat directive should be on the tr element and not the td.
<tr data-ng-repeat="product in products|filter:filter.productName">
Not the cause of your problem, but to log in a service or controller, you can use the $log service and stringify to serialize your objects.
$log.debug(JSON.stringify($scope.products));

Looking at your code, you do $scope.products = [] right at the beginning. This will make angular watch the empty array.
In your init function you assign the products array to $scope.products. But as angular is still watching the initial array it will not be aware of the change.
The solution is to delete the initial assignment $scope.products = [] and make sure to alter the original array but never set it to a new array.
BTW: you could do console.log(JSON.stringify($scope.products)) to get better log information.

Related

How do I get ng-init to work with mutiple functions in a controller?

My html:
<div ng-app="APSApp" class="container">
<br />
<br />
<input type="text" placeholder="Search Terms" />
<br />
<div ng-controller="APSCtl" >
<table class="table">
<tr ng-repeat="r in searchTerms" ng-init="searchTerms=getSearchTerms()" >
<td>{{r.DisplayText}} <input type="text" ng-model="r.SearchInput"></td>
</tr>
</table>
</div>
</div>
<script type="text/javascript">
const moduleId = '#Dnn.ModuleContext.ModuleId';
const tabId = '#Dnn.ModuleContext.TabId';
</script>
<script src="/DesktopModules/RazorCart/Core/Content/Scripts/angular.min.js"></script>
<script src="/DesktopModules/MVC/AdvancedProductSearchMVC/Scripts/AdvancedProductSearch.js"></script>
My angular setup:
var aps = angular.module("APSApp", []);
aps.config(function($httpProvider) {
$httpProvider.defaults.transformRequest = function(data) {
return data !== undefined ? $.param(data) : null;
};
});
aps.factory('SearchTerms',
function($http) {
return {
getSearchTerms: function(onSuccess, onFailure) {
const rvtoken = $("input[name='__RequestVerificationToken']").val();
$http({
method: "post",
url: "/DesktopModules/MVC/AdvancedProductSearchMVC/AdvancedProductSearch/GetAPS",
headers: {
"ModuleId": moduleId,
"TabId": tabId,
"RequestVerificationToken": rvtoken
}
}).success(onSuccess).error(onFailure);
}
};
});
aps.controller('APSCtl',
function(SearchTerms, $scope) {
function getSearchTerms() {
$scope.searchTerms = [];
successFunction = function(data) {
$scope.searchTerms = data;
console.log($scope.searchTerms);
};
failureFunction = function(data) {
console.log('Error' + data);
};
SearchTerms.getSearchTerms(successFunction, failureFunction);
}
function doSomethingElse($scope) {}
});
I'm trying to create a single controller with multiple functions. This works if my angular controller looks like this (and I don't use ng-init):
aps.controller('APSCtl',
function(SearchTerms, $scope) {
$scope.searchTerms = [];
successFunction = function(data) {
$scope.searchTerms = data;
console.log($scope.searchTerms);
};
failureFunction = function(data) {
console.log('Error' + data);
};
SearchTerms.getSearchTerms(successFunction, failureFunction);
});
I was just trying to keep related functions in a single controller. What am I doing wrong? Do I actually have to set up a different controller for each function?
You do not have to assign the value in the template, you can just call the function,
<table class="table" ng-init="getSearchTerms()>
<tr ng-repeat="r in searchTerms" >
<td>{{r.DisplayText}} <input type="text" ng-model="r.SearchInput"></td>
</tr>
</table>
you should have a function named getSearchTerms() in your controller to get it called,
aps.controller('APSCtl',
function(SearchTerms, $scope) {
$scope.getSearchTerms() {
$scope.searchTerms = [];
successFunction = function(data) {
$scope.searchTerms = data;
console.log($scope.searchTerms);
};
failureFunction = function(data) {
console.log('Error' + data);
};
SearchTerms.getSearchTerms(successFunction, failureFunction);
}
function doSomethingElse($scope) {}
});

Angularjs: pass variable between controlers and reloading data

In my application the user can do a search. When the search field is filled, a query is executed and a loading message appears until the complete execution of the request. This part is working perfectly.
I'm trying to pass the search string to another controller in order to come back on the main part with the previous results. This is working too but I don't know if I have used the best way...
MY PROBLEM: when I come back on the main part (search section), during the data reloading, the loading message is not displayed anymore, could you please help me to solve and update the code ?
Here my controller:
var app=angular.module('ContactsApp', ['ngRoute', 'ui.bootstrap', 'ngDialog']);
app.config(function($routeProvider, $httpProvider, ngDialogProvider){
$httpProvider.defaults.cache = false;
if (!$httpProvider.defaults.headers.get) {
$httpProvider.defaults.headers.get = {};
}
// disable IE ajax request caching
$httpProvider.defaults.headers.get['If-Modified-Since'] = '0';
ngDialogProvider.setDefaults({
className: 'ngdialog-theme-default',
plain: false,
showClose: true,
closeByDocument: true,
closeByEscape: true,
appendTo: false,
preCloseCallback: function () {
console.log('default pre-close callback');
}
});
//$httpProvider.requestInterceptors.push('httpRequestInterceptorCacheBuster');
// Add the interceptor to the $httpProvider to intercept http calls
$httpProvider.interceptors.push('HttpInterceptor');
$routeProvider.when('/all-contacts',
{
templateUrl: 'template/allContacts.html',
controller: 'ctrlContacts',
})
.when('/view-contacts/:contactId',
{
templateUrl: 'template/viewContact.html',
controller: 'ctrlViewContacts'
})
.otherwise({redirectTo:'/all-contacts'});
});
app.factory('httpInterceptor', function ($q, $rootScope, $log) {
var numLoadings = 0;
return {
request: function (config) {
numLoadings++;
// Show loader
$rootScope.$broadcast("loader_show");
return config || $q.when(config)
},
response: function (response) {
if ((--numLoadings) === 0) {
// Hide loader
$rootScope.$broadcast("loader_hide");
}
return response || $q.when(response);
},
responseError: function (response) {
if (!(--numLoadings)) {
// Hide loader
$rootScope.$broadcast("loader_hide");
}
return $q.reject(response);
}
};
})
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
});
//LOADING ICON DURING LOADING DATA
app.directive("loader", function ($rootScope) {
return function ($scope, element, attrs) {
$scope.$on("loader_show", function () {
return element.show();
});
return $scope.$on("loader_hide", function () {
return element.hide();
});
};
}
)
//DIRECTIVE FOR PASSING A VARIABLE BETWEEN CONTROLER
app.factory('MyTextSearch', function() {
// private
var value = '';
// public
return {
getValue: function() {
return value;
},
setValue: function(val) {
value = val;
}
};
})
app.controller('ctrlContacts', function ($scope, MyTextSearch, ContactService){
$scope.searchText = "Search Name...";
console.log("INIT SEARCH:" + MyTextSearch.getValue() );
$scope.contacts=null;
$scope.searchButtonText = "Search";
$scope.test = false;
$scope.reSearch = function () {
// Do your searching here
// simulate search
$timeout(function () {
// search is complete
}, 2000);
}
function searchContact(searchText) {
// GET THE VALUE OF THE VARIABLE PASS TO THE CONTROLERS
MyTextSearch.setValue(searchText);
console.log("NEW SEARCH:" + searchText);
if (!searchText.length) {
$scope.stringToSearch="Search Name...";
}
if (searchText.length>2) {
$scope.loading = true;
$scope.test = true;
$scope.searchButtonText = "Loading...";
ContactService.fastSearch(searchText).success(function(contacts){
var length = contacts.length;
$scope.loading = false;
if (length == 0) {
$scope.searchButtonText = "No result";
}else {
$scope.searchButtonText = length + " results found";
}
// For the orderby date
for (var i=0; i<length; i++) {
if(contacts[i].REQUESTTRUEDATE!=""){
contacts[i].REQUESTTRUEDATE = new Date(contacts[i].REQUESTTRUEDATE.replace(/-/g,"/"));
}else{
contacts[i].REQUESTTRUEDATE=null;
}
}
$scope.contacts = contacts;
$scope.selIdx= -1;
$scope.selContact=function(contact,idx){
$scope.selectedContact=contact;
$scope.selIdx=idx;
window.location="#/view-contacts/" + idx;
}
$scope.isSelContact=function(contact){
return $scope.selectedContact===contact;
}
});
}else{
$scope.contacts=null;
}
}
if(MyTextSearch.getValue().length!=0){
// When come back on the result lists
var stringToSearch = MyTextSearch.getValue();
$scope.search = searchContact(stringToSearch);
//Usefull for reloading query if stringToSearch is updated
$scope.search = function(stringToSearch){
searchContact(stringToSearch);
}
}else{
// New search
$scope.search = function(searchText){
searchContact(searchText);
}
}
// recherche
$scope.searchText = null;
$scope.razRecherche = function() {
$scope.searchText = null;
console.log("RAZ");
MyTextSearch.setValue('');
$scope.contacts=null;
}
});
app.controller('ctrlViewContacts', function ($scope, $routeParams, MyTextSearch, ContactService, RequestService, ReportService){
// GET THE VALUE OF THE PREVIOUS SEARCH
$scope.searchText = MyTextSearch.getValue();
console.log("SEARCHTEXT: " + $scope.searchText );
$scope.contact = null;
ContactService.loadPersonById($routeParams.contactId).success(function(contact){
$scope.contact = contact;
});
});
Here my view:
<h3>View all contacts</h3>
<div class="spacer input-group">
<div class="input-group-addon">
<span class="glyphicon glyphicon-search"></span>
</div>
<input type="text" ng-model="searchText" class="form-control" placeholder="Search name..." ng-change="search(searchText)"/>
<div class="input-group-btn">
<button class="btn btn-default" ng-click="razRecherche()">
<span class="glyphicon glyphicon-remove"></span>
</button>
</div>
</div>
<div ng-show="(!searchText || (searchText.length)<3) && contacts==null && !searchButtonText" id="least3Characters">
<p class="spacer center"><strong>Please enter at least 3 characters</strong></p>
</div>
<div>
<p class="spacer center" ng-show="searchText && (searchText.length)>2" >
<img src="../img/loading.gif" class="ajax-loader" ng-show="loading==true"/>
<strong>{{ searchButtonText }}</strong>
</p>
</div>
<div class="table-responsive" id="allContacts">
<table ng-show="contacts.length" class="table table-striped table-hover spacer">
<thead>
<tr>
<th class="colPerson">
Person
<span class="hSpacer" ng-class="cssChevronsTri('PERSON')"></span>
</th>
<th class="colCompany">
Company
<span class="hSpacer" ng-class="cssChevronsTri('COMPANY')"></span>
</th>
<th class="colAction">Action</th>
</tr>
</thead>
<tbody ng-repeat="contact in contacts | filter:searchText | orderBy:champTri:triDescendant"
>
<tr class="clickable">
<td class="colPerson" ng-click="selContact(contact,contact.ID)" ng-class="{sel:selIdx==$index}">{{contact.PERSON}}</td>
<td class="colCompany" ng-click="selContact(contact,contact.ID)">{{contact.COMPANY}}</td>
<td class="colAction">
<span class="glyphicon glyphicon-pencil"></span>
<button class="inline btn btn-default" data-ng-click="confirmDelPerson(contact.ID, contact.NBREQUEST)">
<span class="glyphicon glyphicon-remove"></span>
</button>
</td>
</tr>
</tbody>
</table>
</div>
Many Thanks in advance for your help.

Add, Remove & Update specific data In JSON in AngularJS

I have pulled data from json file. Now its displayed over DOM.
On HTML Page, I have three option 1) Edit Data 2) Delete Particular Data & 3) Add New Data.
How to perform this using AngularJS Code? i.e. on editing name, it should update my JSON object. On Deleting row, it should delete that row in JSON data. and also If I click on Add New, then entered data will be added to JSON.
My Code is as below.
Importing data through json file and displaying on DOM
.controller('MainCtrl', function ($scope, $http) {
$http.get('data/home.json').
success(function(data, status, headers, config) {
$scope.details = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
Output of this code is correct as below image.
JSON Object as below.
{
"status":"success",
"adformat":[
{
"adformat_id":1,
"name":"Format 1",
"size":"300x250"
},
{
"adformat_id":2,
"name":"Format 2",
"size":"320x250"
},
{
"adformat_id":3,
"name":"Format 3",
"size":"320x480"
}
]
}
I would do it like this:
MainCtrl.js
(function () {
'use strict';
angular
.module('app')
.controller('MainCtrl', MainCtrl);
MainCtrl.$inject = ['$scope', 'MainFactory'];
function MainCtrl($scope, MainFactory) {
$scope.details = MainFactory.details;
function init() {
MainFactory.get();
}
init();
$scope.detailsModel = {
"adformat_id": 1,
"name": "Format 1",
"size": "300x250"
};
$scope.add = function () {
$scope.details.push($scope.detailsModel);
};
$scope.delete = function (index) {
$scope.details.splice(index, 1);
};
$scope.edited = -1;
$scope.editedModel = {
"adformat_id": 0,
"name": "",
"size": ""
};
$scope.edit = function (index) {
$scope.edited = index;
};
$scope.finishEdit = function (index) {
$scope.details[index] = $scope.editedModel;
$scope.edited = -1;
};
}
})();
MainFactory.js
(function () {
'use strict';
angular
.module('app')
.factory('MainFactory', MainFactory);
MainFactory.$inject = [];
function MainFactory() {
var self = this;
self.details = [];
self.get = $http.get('data/home.json')
.then(function (response) {
self.details = response.data;
}).catch(function (error) {
// log error
});
return self;
}
})();
index.html
<div ng-app="app">
<div ng-controller="MainCtrl">
<table>
<tbody>
<tr ng-repeat="details in detail">
<!-- show-->
<td ng-hide="edited === $index">{{detail.adformat_id}}</td>
<td ng-hide="edited === $index">{{detail.name}}</td>
<td ng-hide="edited === $index">{{detail.size}}</td>
<td ng-hide="edited === $index">
<button ng-click="edit($index)">Edit</button>
<button ng-click="delete($index)">Detele</button>
</td>
<!-- Edit-->
<td ng-show="edited === $index">{{detail.adformat_id}}</td>
<td ng-show="edited === $index"><input type="text" ng-model="editedModel.name"></td>
<td ng-show="edited === $index"><input type="number" ng-model="editedModel.size"></td>
<td ng-show="edited === $index">
<button ng-click="finishEdit($index, editedModel)">Save</button>
<button ng-click="delete($index)">Detele</button>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<button ng-click="add()">Add</button>
</td>
</tr>
</tfoot>
</table>
</div>
</div>
It is just prototype, not tested, but it should help you to understand idea o two way binding in angular.
Here is my approach to this requirement. Let me know if any further improvement can be added. The entire code can be found at the below URL:
Angular Save, Update and Delete
The sample screenshots from the code can be found here...
controller:
'use strict';
function MainController($scope, SharedService, ngDialog) {
$scope.account_type_selected = "Savings";
$scope.sharedService = SharedService;
$scope.savingsMain = [];
$scope.checkingsMain = [];
$scope.addToCheckingsAccounts = {};
$scope.addToSavingsAccounts = {};
$scope.setAccountType = function (type) {
if (type === "allAccounts") {
$scope.showSavings = true;
$scope.showCheckings = true;
} else if (type === "savingsAccounts") {
$scope.showSavings = true;
$scope.showCheckings = false;
} else if (type === "checkingAccounts") {
$scope.showSavings = false;
$scope.showCheckings = true;
}
$scope.account_type_selected = type;
};
$scope.$watch('savingsMain', function ($scope) {
return $scope.savingsMain;
});
$scope.selectedAccountType = function (showAccount) {
console.log(showAccount);
if (showAccount === "Savings") {
$scope.sharedService.accountType = "Savings";
} else {
$scope.sharedService.accountType = "Checkings";
}
};
$scope.saveAccounts = function () {
if ($scope.sharedService.accountType === "Savings") {
$scope.addToSavingsAccounts = {
"account_type": $scope.sharedService.accountType,
"amount": $scope.sharedService.amount,
"date": $scope.sharedService.date,
"maturity": $scope.sharedService.maturity
};
$scope.showSavings = true;
$scope.savingsMain.push($scope.addToSavingsAccounts);
} else {
$scope.addToCheckingsAccounts = {
"account_type": $scope.sharedService.accountType,
"amount": $scope.sharedService.amount,
"bic": $scope.sharedService.BIC,
"iban": $scope.sharedService.IBAN
};
$scope.showCheckings = true;
$scope.checkingsMain.push($scope.addToCheckingsAccounts);
}
ngDialog.close();
};
$scope.deleteDataFromSharedService = function (accountType, item) {
if (accountType === "Savings") {
$scope.savingsMain = _.without($scope.savingsMain, _.findWhere($scope.savingsMain, { date: item }));
} else if (accountType === "Checkings") {
$scope.checkingsMain = _.without($scope.checkingsMain, _.findWhere($scope.checkingsMain, { bic: item }));
}
};
$scope.closeDialog = function () {
ngDialog.close();
};
$scope.accountTypeModel = [];
$scope.prop = {
"type": "select",
"name": "account_type",
"value": $scope.sharedService.accountType,
"accountTypeData": ["Savings", "Checkings"]
};
}
<form ng-controller="MainController">
<div class="page-header">
<h1>Angular-Save-Update-Delete</h1>
</div>
<div class="content-wrapper">
<div class="sidebar">
<table>
<tbody>
<tr>
<td>
<button ng-click="setAccountType('allAccounts')" ng-model="allAccounts" class="ng-pristine ng-untouched ng-valid ng-empty">All</button>
</td>
</tr>
<tr>
<td>
<button ng-click="setAccountType('savingsAccounts')" ng-model="savingsMain" class="ng-pristine ng-valid ng-not-empty ng-touched">Savings</button>
</td>
</tr>
<tr>
<td>
<button ng-click="setAccountType('checkingAccounts')" ng-model="checkingsMain" class="ng-pristine ng-untouched ng-valid ng-not-empty">Checkings</button>
</td>
</tr>
<tr>
<td>
<button class="create-account-btn-class"
type="button"
ng-dialog="app/views/create-account-template.html"
ng-dialog-data=""
ng-dialog-class="ngdialog-theme-default"
ng-dialog-scope="this"
plain=false
showClose=true
closeByDocument=true
closeByEscape=true
ng-dialog-show-close="false">New Account</button>
</td>
</tr>
</tbody>
</table>
</div>
<div class="right-content">
<div id="savingsTemplate" templateurl="app/views/savings.html" ng-show="showSavings" include-template=""></div>
<div id="checkingsTemplate" templateurl="app/views/checkings.html" ng-show="showCheckings" include-template=""></div>
</div>
</div>
</form>

Angular Two Way Data Binding Not Working While Using HTTP

I am using ControllerAs in angular with ui.router, I have an API in PHP when I call the API and set the scope variable by vm approach for templates then it works accordingly and when I want to delete some record set
and update the vm.servers variable again then template not change according to the newly updated object.
function serverController( server, $state, $rootScope, $scope)
{
var vm = this;
vm.delete = function(server_id) {
vm.loader = false;
server.delete('server/' + server_id)
.then(
function(response){
if(response.status === 200 && !response.data.status) {
alert(response.data.message);
} else if(response.status === 200 && response.data.status){
server.setRootScope().then(
function(){
vm.servers = $rootScope.servers;
$state.go($state.current, {}, {reload: true});
}
);
}
}, function(response) {
if(response.status === 401) {
$state.go('login');
}
}
);
};
if($rootScope.servers == undefined) {
server.get('server')
.then(
function (response) {
if (response.status === 200) {
vm.servers = response.data;
$rootScope.servers = {};
angular.forEach(response.data, function (val) {
if('running' === val.status) {
val['serverState'] = true;
} else {
val['serverState'] = false;
}
$rootScope.servers[val.id] = val;
});
}
},
function (response) {
if (response.status === 401) {
$state.go('login');
}
});
} else {
vm.servers = $rootScope.servers;
}
}
Template File.
<table class="table movietable" width="70%" border="1">
<tr ng-repeat="server in serverModel.servers">
<td width="85%">
<table>
<tr>
<td><b>Server Label: </b> {{server.label}}</td>
</tr>
<tr>
<td>Status: {{server.status}}</td>
</tr>
<tr>
<td>Created At: {{server.created_at}}</td>
</tr>
</table>
</td>
</tr>
</table>
I look your code. I found a problem that,
You are not updating the vm.servers with
the response data. As the values in $rootScope.servers might
be older. So with every delete function call you will have to either update the $rootScope.servers or vm.servers with new data.
I have create a small demo from your code, hope it will help you
identify the problem. In this demo I have first load the data in table
after this, on a button click deleting the record by id and updating
the vm.servers.
My Controller
.controller('Controller',['$rootScope', function($rootScope) {
var vm =this;
vm.customer = {
name: 'Naomi',
address: '1600 Amphitheatre'
};
vm.delete = function(server_id) {
vm.loader = false;
// added some value to $rootScope.servers or you can update it with response data. This is where you will need to update your logic.
$rootScope.servers = [
{ id: 1,
name: 'Naomi1',
address: '1600 Amphitheatre1'
},
{
id: 2,
name: 'Naomi2',
address: '1600 Amphitheatre2'
}
];
angular.forEach($rootScope.servers, function(value,key) {
if(value.id == server_id) {
$rootScope.servers.splice(key,1);
}
});
console.log($rootScope.servers);
//Here I have assign new $rootScope.servers.
vm.servers = $rootScope.servers;
};
var val = {};
vm.init = function() {
vm.servers = [{
id: 1,
name: 'Naomi1',
address: '1600 Amphitheatre1'
},{
id: 2,
name: 'Naomi2',
address: '1600 Amphitheatre2'
}];
$rootScope.servers = {};
val['serverState'] = true;
$rootScope.servers[val.id] = val;
}
vm.init();
}])
index.html
<div ng-controller="Controller as vm">
<table class="table movietable" width="70%" border="1">
<tr>
<td width="85%">
<table>
<tr ng-repeat="server in vm.servers">
<td><b>Server Label: </b> {{server.name}}</td>
<td>Status: {{server.address}}</td>
<td><button ng-click="vm.delete(server.id);">Delete</button></td>
</tr>
</table>
</td>
</tr>
</table>
</div>
Hope this will help you !
Cheers,
Jimmy

AngularJS ~ Refresh pagination after Ajax request

I 'm a beginner in AngularJS. I have created a page that retrieves records from database along with total records using an Ajax call. After populating the grid with the records, I wanted to refresh the pager control based on values received from the Ajax call such as the total records and the current page number as 1. I'm seeing the pager but is not refreshed. Can you please verify and let me know what I'm missing here?
var angularPersonModule = angular.module("angularPersonModule", ['ui.bootstrap']);
angularPersonModule.controller("AngularPersonController", AngularPersonController);
angularPersonModule.controller("PaginationController", PaginationController);
angularPersonModule.factory("PaginationService", PaginationService);
PaginationController.$inject = ['$scope', '$timeout', '$rootScope', 'PaginationService'];
function PaginationController($scope, $timeout, $rootScope, PaginationService) {
$scope.setPage = function(pageNo) {
if ($scope.currentPage === pageNo) {
return;
}
$scope.currentPage = pageNo;
$rootScope.$broadcast("personPageChanged", $scope.currentPage);
alert("call from setPage");
};
$scope.pageChanged = function() {
var i = 0;
};
$scope.$on('personRefreshPagerControls', function(event, args) {
//the solution:
setTimeout(function() {
//setTimeout is a deffered call (after 1000 miliseconds)
$timeout(function() {
$scope.totalItems = PaginationService.getTotalRecords();
$scope.currentPage = PaginationService.getPageNumber();
$scope.itemsPerPage = PaginationService.getPageSize();
$scope.numPages = PaginationService.getPageCount();
alert("totalItems = " + $scope.totalItems);
alert("currentPage = " + $scope.currentPage);
alert("itemsPerPage = " + $scope.itemsPerPage);
alert("pageCount = " + $scope.numPages);
});
}, 900);
});
}
AngularPersonController.$inject = ['$scope', '$rootScope', 'AngularPersonService', 'PaginationService'];
function AngularPersonController($scope, $rootScope, AngularPersonService, PaginationService) {
$scope.getAll = function() {
$scope.persons = AngularPersonService.search();
PaginationService.setTotalRecords(3);
PaginationService.setPageNumber(1);
PaginationService.setPageSize(2);
PaginationService.setPageCount(2);
$rootScope.$broadcast("personRefreshPagerControls", 3);
}
$scope.$on('personPageChanged', function(event, args) {
alert("pageChanged Event fired");
alert("Received args = " + args);
$scope.getAll();
});
$scope.getAll();
}
function PaginationService() {
var currentPage = 1;
var pageCount = 2;
var pageSize = 2;
var totalRecords = 3;
return {
getPageNumber: function() {
return currentPage;
},
setPageNumber: function(pageNumber) {
currentPage = pageNumber;
},
getPageSize: function() {
return pageSize;
},
setPageSize: function(newPageSize) {
pageSize = newPageSize;
},
getTotalRecords: function() {
return totalRecords;
},
setTotalRecords: function(newTotalRecords) {
totalRecords = newTotalRecords;
},
getPageCount: function() {
return pageCount;
},
setPageCount: function(newPageCount) {
pageCount = newPageCount;
}
}
}
angularPersonModule.factory("AngularPersonService", function($http) {
return {
search: function() {
return [{
"Name": "Hemant"
}, {
"Name": "Ashok"
}, {
"Name": "Murugan"
}];
}
}
});
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-route.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-resource.min.js"></script>
<script src="https://raw.github.com/angular-ui/bootstrap/gh-pages/ui-bootstrap-0.14.3.js"></script>
<script src="https://raw.githubusercontent.com/angular-ui/bootstrap/gh-pages/ui-bootstrap-tpls-0.14.3.js"></script>
<div ng-app="angularPersonModule">
<div class="panel panel-default">
<div class="panel-body" ng-controller="AngularPersonController">
<table class="table table-striped table-hover">
<thead>
<tr>
<th class="col-md-3">
Name
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in persons">
<td>
<span>{{person.Name}}</span>
</td>
</tbody>
</table>
</div>
</div>
<div ng-controller="PaginationController">
<uib-pagination total-items="totalItems" ng-model="currentPage" ng-change="pageChanged()"></uib-pagination>
</div>
</div>
Update
Now I have updated the snippet so that you can execute and see the result manually.

Resources