Angular controller won't update the view for some reason - angularjs

I have a service that looks like:
myApp.service('peerService', [
'$http', function($http) {
this.getPeers = function() {
return $http({
url: '/api/v1/peers',
method: 'GET'
});
};
}
]);
In my controller, I have:
myApp.controller('PeerComparisonController', [
'$scope', '$rootScope', 'peerService', function($scope, $rootScope, peerService) {
$scope.init = function() {
$rootScope.pageTitle = 'Peer Comparison';
return $scope.peers = [];
};
$scope.getPeers = function() {
return peerService.getPeers().then(function(response) {
console.log(response);
return $scope.peers = response.data;
});
};
return $scope.init();
}
]);
My view has {{ peers }} in it. This does not get updated when the service returns. I've tried:
peerService.getPeers().then(function(response) {
return $scope.$apply(function() {
return $scope.peers = response.data;
});
});
And that also doesn't work. So any ideas?

you try something like this
myApp.service('peerService', [
'$http', function($http) {
this.getPeers = function() {
return $http({method: 'GET', url:'/api/v1/peers'}).
then(function(response) {
return response.data;
});
};
}
]);
or
myApp.service('peerService', ['$http', function ($http) {
this.getPeers = function () {
var deferred = $q.defer();
$http({ method: 'GET', url: '/api/v1/peers' }).
then(function (response) {
deferred.resolve(response.data);
});
return deferred.promise;
};
}
]);

Related

separated controller from component

Component:
crudModule.js
var crudModule = angular.module('crudModule', ['ui.router', 'smart-table', 'ngCookies', 'ui.bootstrap', 'angularModalService', 'dialogs', 'remoteValidation']);
angular.module('crudModule').component('applicationInfo', {
templateUrl: 'infoApplication.html',
controller: 'applicationInfoCtrl'
});
applicationInfoCtrl.js:
var crudModule = angular.module('crudModule')
crudModule.controller('applicationInfoCtrl', ['httpService', '$scope', function($http, $scope, $cookies, $stateParams, httpService) {
httpService.httpGetRequest("http://localhost:8080/applications/" + $stateParams.id).then(function success(response) {
$scope.application = response.data;
});
$scope.getApiKey = function () {
httpService.httpGetRequest('http://localhost:8080/applications/generateApiKey').then(function success(response) {
$scope.application.apikey = response.data.apikey;
$scope.application.apisecret = response.data.apisecret
})
};
$scope.send = function (object, url) {
httpService.httpPostRequest(object, url + "/" + $stateParams.id).catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
}).then(function success(response){
});
}
}]);
httpService.js:
var crudModule = angular.module('crudModule')
crudModule.factory('httpService', function($http) {
return {
httpGetRequest: function (url) {
return $http({
method: 'GET',
url: url
})
},
httpPostRequest: function (object, url){
return $http({
method:'POST',
url: url,
data: object
})
}
}
});
I am getting error:
Cannot read property 'httpGetRequest' of undefined.
I have injected my httpService and i dont find any mistakes yet
The problem is the order of parameters in your controller, it should be
crudModule.controller('applicationInfoCtrl', ['$http','httpService', '$scope','$cookies','$stateParams' function(http,httpService, $scope,$cookies,$stateParams) {
}

update q defer promise before returning

I call getBookIDs from factory and by using the result I call getBookInfo from the same factory. but in the Console.log(bookInfo) it shows me the result of previous call!
how can I update the deferred.promise value before returning??
this is my controller
angular.module('myApp.products',[])
.controller('productController', function ($scope , MainFactory , $location) {
function getBookInfo(bookIDs){
MainFactory.getBookList(bookIDs)
.then(function (bookInfo) {
console.log(bookInfo)
})
}
MainFactory.getBookIDs()
.then(function (result) {
$scope.bookIDList = result;
getBookInfo($scope.bookIDList);
});
});
and this is my factory
app = angular.module('myApp');
app.factory("MainFactory", ['$soap', '$http', '$q', function ($soap, $http, $q) {
var viewFactory = {};
var deferred = $q.defer();
viewFactory.getBookIDs = function () {
//var bookIDs = [];
$http({
url: 'http://127.0.0.1/client.php?fn=getBooks',
method: "GET"
}).then(function success(response) {
deferred.resolve(response.data.result);
}, function myError(error) {
console.log('error', error);
});
return deferred.promise;
};
viewFactory.getBookList = function (bookIDs) {
$http({
url: 'http://127.0.0.1/client.php?fn=getBooksInfo&p1=' + bookIDs,
method: "GET"
}).then(function success(response) {
deferred.resolve(response.data.result);
}, function myError(error) {
deferred.reject(error);
});
return deferred.promise;
};
return viewFactory;
}]);
You should return a new promise for each of your service methods:
app.factory("MainFactory", ['$soap', '$http', '$q', function ($soap, $http, $q) {
var viewFactory = {};
viewFactory.getBookIDs = function () {
var deferred = $q.defer();
//var bookIDs = [];
$http({
url: 'http://127.0.0.1/client.php?fn=getBooks',
method: "GET"
}).then(function success(response) {
deferred.resolve(response.data.result);
}, function myError(error) {
console.log('error', error);
});
return deferred.promise;
};
viewFactory.getBookList = function (bookIDs) {
var deferred = $q.defer();
$http({
url: 'http://127.0.0.1/client.php?fn=getBooksInfo&p1=' + bookIDs,
method: "GET"
}).then(function success(response) {
deferred.resolve(response.data.result);
}, function myError(error) {
deferred.reject(error);
});
return deferred.promise;
};
return viewFactory;
}]);
Promises should not be reused (unless you wish to perform multiples tasks triggering the same resolve/reject... still, you should explicitly implement a promise aggregator for that, I think).
All angular services are singletons, so i guess the reason you got this bug is getBookIDs and getBookList share the same deferred
try change your factory to
app.factory("MainFactory", ['$soap', '$http', '$q', function ($soap, $http, $q) {
var viewFactory = {};
viewFactory.getBookIDs = function () {
//var bookIDs = [];
var deferred = $q.defer();
$http({
url: 'http://127.0.0.1/client.php?fn=getBooks',
method: "GET"
}).then(function success(response) {
deferred.resolve(response.data.result);
}, function myError(error) {
console.log('error', error);
});
return deferred.promise;
};
viewFactory.getBookList = function (bookIDs) {
var deferred = $q.defer();
$http({
url: 'http://127.0.0.1/client.php?fn=getBooksInfo&p1=' + bookIDs,
method: "GET"
}).then(function success(response) {
deferred.resolve(response.data.result);
}, function myError(error) {
deferred.reject(error);
});
return deferred.promise;
};
return viewFactory;
}]);

AngularJS retrieve data from backend using factory/service

I'm approaching AngularJS and I want to get data from a database. I succeeded in doing this
angular.module("myApp")
.controller("listaUtentiCtrl", function($scope, $http) {
$http.get("backListaUtenti.php").success(function(data) { $scope.utenti=data } )
});
but I'd like to use a factory / service in order use the data from multiple controllers (but is not working)
angular.module("myApp")
.factory("utentiService", function($http,$q) {
var self = $q.defer();
$http.get("backListaUtenti.php")
.success(function(data){
self.resolve(data);
})
.error(function(){
alert("Error retrieving data!");
})
return self.promise;
});
angular.module("myApp")
.controller("utenteCtrl", function($scope, $routeParams, utentiService, filterFilter) {
var userId = $routeParams.userId;
$scope.utente = filterFilter(utentiService.utenti, { id: userId })[0];
});
angular.module("myApp")
.controller("listaUtentiCtrl", function($scope, utentiService) {
$scope.utenti = utentiService.utenti;
});
Where am I failing?
The problem is in your service implementation. Here is your code refactored:
angular.module("myApp")
.factory("utentiService", function($http) {
return {
getData: function () {
return $http.get("backListaUtenti.php").then(function (response) {
return response.data;
});
}
};
});
angular.module("myApp")
.controller("utenteCtrl", function($scope, $routeParams, utentiService, filterFilter) {
var userId = $routeParams.userId;
utentiService.getData().then(function(data) {
$scope.utente = filterFilter(data, { id: userId })[0];
});
});
angular.module("myApp")
.controller("listaUtentiCtrl", function($scope, utentiService) {
utentiService.getData().then(function (data) {
$scope.utenti = data;
});
});
If your data is static you can cache the request and avoid unnecessary requests like this:
$http.get("backListaUtenti.php", { cache: true });

$window.location.href is undefined with angularjs

I programme an application in ASP.NET MVC6, angularjs and Bootstap.
I want reload a page after bootstrap modal closing.
To do this, I use $window.location.href but it's undefined.
This is my method in angular Controller:
angular
.module('LSapp')
.controller('CustomersCtrl', CustomersCtrl);
CustomersCtrl.$inject = ['$scope', '$http', '$location', '$modal', '$templateCache', '$window'];
function CustomersCtrl($scope, $http, $location, $modal, $window) {
$scope.edit = function(id)
{
var customer = getCustomer(id);
console.log('Customer => FirstName : ' + customer.FirstName);
var reqEditCustomer = $http({ url: '/api/customers/', dataType: 'json', method: 'PUT', data: JSON.stringify(customer), contentType: 'application/json; charset=utf-8' });
reqEditCustomer.success(function (dataResult) {
$scope.customer = dataResult;
$scope.cancel();
});
$scope.customers = getListCustomers();
$window.location.href = '/';
}
}
All runs except the redirection.
I hope someone can help me . Any help is welcome.
you can use
$location.path('/');
instead of
$window.location.href = '/';
Try This -
$location.path('/').replace();
if(!$scope.$$phase) $scope.$apply()
I tried to redirect since a view and not a modal. It's work.
So I think it's redirect with my modal who create problem.
It's my full controller:
(function () {
'use strict';
angular
.module('LSapp')
.controller('CustomersCtrl', CustomersCtrl)
.controller('CustomersGetCtrl', CustomersGetCtrl);
CustomersCtrl.$inject = ['$scope', '$http', '$location', '$modal', '$templateCache', '$window'];
function CustomersCtrl($scope, $http, $location, $modal, $window) {
/*---------------------------------------------------------------------------------
* Obtain Customer List
*--------------------------------------------------------------------------------*/
function getListCustomers()
{
var reqCustomers = $http.get('/api/Customers');
reqCustomers.success(function (dataResult) {
$scope.customers = dataResult;
});
return $scope.customers;
}
getListCustomers();
/*---------------------------------------------------------------------------------
* Obtain Customer by ID
*--------------------------------------------------------------------------------*/
function getCustomer(id) {
var reqGetCustomer = $http({ url: '/api/customers/' + id, method: 'GET' });
reqGetCustomer.success(function (dataResult) {
$scope.customer = dataResult;
})
return $scope.customer;
}
$scope.edit = function(id)
{
var customer = getCustomer(id);
console.log('Customer => FirstName : ' + customer.FirstName);
var reqEditCustomer = $http({ url: '/api/customers/', dataType: 'json', method: 'PUT', data: JSON.stringify(customer), contentType: 'application/json; charset=utf-8' });
reqEditCustomer.success(function (dataResult) {
$scope.customer = dataResult;
$scope.cancel();
});
$scope.customers = getListCustomers();
//This is that I tried to redirect
//$window.location.href = '/';
//$location.path('/').replace();
//if(!$scope.$phase) $scope.$apply
}
/*---------------------------------------------------------------------------------
* Manage Customer Details Modal
*--------------------------------------------------------------------------------*/
$scope.openDetails = function (id) {
var modalInstance = $modal.open({
templateUrl: 'Modals/Customers/details.html',
controller: $scope.modalDetails,
resolve: {
id: function () {
return id
}
}
});
}
$scope.modalDetails = function($scope, $modalInstance, id)
{
if (angular.isDefined(id)) {
var reqGetCustomer = $http({ url: '/api/Customers/' + id, method: 'GET' });
reqGetCustomer.success(function (dataResult) {
$scope.customer = dataResult;
});
} else { alert('id is undefined'); }
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
}
}
/*---------------------------------------------------------------------------------
* Manage Customer Edit Modal
*--------------------------------------------------------------------------------*/
$scope.openEdit = function (id) {
var modalInstance = $modal.open({
templateUrl: 'Modals/Customers/edit.html',
controller: $scope.modalEdit,
resolve: {
id: function () {
return id
}
}
});
}
$scope.modalEdit = function ($scope, $modalInstance, id) {
if (angular.isDefined(id)) {
var reqGetCustomer = $http({ url: '/api/Customers/' + id, method: 'GET' });
reqGetCustomer.success(function (dataResult) {
$scope.customer = dataResult;
});
} else { alert('id is undefined'); }
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
}
}
}
//Controller to redirect since View
CustomersGetCtrl.$inject = ['$scope', '$http', '$routeParams', '$window'];
function CustomersGetCtrl($scope, $http, $routeParams, $window)
{
function getCustomer()
{
var reqGetCustomer = $http({ url: '/api/customers/' + $routeParams.id, method: 'GET' })
reqGetCustomer.success(function (dataResult) {
$scope.customer = dataResult;
})
}
getCustomer();
$scope.edit = function () {
$window.location.href = '/';
}
}
})();
I solved the problem by using ui.router instead of ng -router.

Moving code from controller to a factory breaks the code, why?

I'm moving my code from the .controller to a factory
here is the code that works from the controller
.controller('ChatsCtrl', function ($scope, $http, $rootScope) {
$http.get('http://<my_ip>:<my_port>/chats', { params: { user_id: $rootScope.session } }).success(function (response) {
$scope.chats = response;
});
})
I want this to be refactored to a factory so the controller looks like this
.controller('ChatsCtrl', function ($scope, Chats) {
$scope.chats = Chats.all();
})
So the factory is like this
.factory('Chats', function() {
return {
all: function ($scope, $http, $rootScope) {
return $http.get('http://<my_ip>:<my_port>/chats', { params: { user_id: $rootScope.session } }).success(function (response) {
$scope.chats = response;
});
}
};
});
So when I move the code to the factory it doesn't pull anything from my database. I have referenced the 'Chats' factory in the controller but it doesn't seem to pull the data through.
Return the promise to set and assign it to the scope in the controller. So more like this.
.controller('ChatsCtrl', function ($scope, Chats) {
Chats.all().success(function (data) {
$scope.chats = data;
})
})
.factory('Chats', function($http, $rootScope) {
return {
all: function () {
return $http.get('http://<my_ip>:<my_port>/chats',
{ params: { user_id: $rootScope.session } })
}
};
});
You can return a promise from the factory and do .success in the controller(optionally with a cache in the factory if your data doesn't change)
.factory('Chats', function() {
return {
all: function ($scope, $http, $rootScope) {
return $http.get('http://<my_ip>:<my_port>/chats', { params: { user_id: $rootScope.session } })
}
};
});
.controller('ChatsCtrl', function ($scope, Chats) {
Chats.all().success(function (response) {
$scope.chats = response;
});
})

Resources