I am using AngularJS to set up a table and filter its data by a search or category keywords. I
AngularJS
categorieFilter = angular.module("categorieFilter", [])
categorieFilter.controller("catFilter", ["$scope", "store", function($scope, store){
$scope.search = "";
$scope.products = [];
$scope.categories = [];
$scope.categories = store.getCategories();
$scope.products = store.getProducts();
$scope.filterProductsByCats = function(category){
$scope.search = category;
};
}])
categorieFilter.factory('store', function($http){
return {
getCategories: $http.get('api/categories').success(function (data) {
return data;
}),
getProducts : $http.get('api/products').success(function (data) {
return data;
}
};
});
The $http.get on its own is working, when I surf directly to my api I get the required data. Also when I do a alert(data) ifter the $hhtp.get in categories, I get the data I need... So this should be working but it doesn't. I get an error:
TypeError: store.getCategories is not a function
And I got no clue where this is coming from. Anybody a solution to this problem?
When using a factory you should do new function to return a constructor:
function myFactoryFunction() {
return function() {
var a = 2;
this.a2 = function() {
return a*2;
};
};
}
---------------------------------------------------------------------------------
// Injected in your controller
var myShinyNewObject = new myInjectedFactory();
$scope.four = myShinyNewObject.a2();
From this detailed post angular.service vs angular.factory
In your case
var storeFactory = new store();
storeFactory.getProducts();
Updated version, with TS code:
categorieFilter = angular.module("categorieFilter", [])
/**
Store factory
*/
categorieFilter.controller("catFilter", ["$scope", "store", function($scope, store){
$scope.search = "";
$scope.products = [];
$scope.categories = [];
store.getCategories().then(function(data){
$scope.categories = data;
})
store.getProducts().then(function(data){
$scope.products = data;
})
$scope.filterProductsByCats = function(category){
$scope.search = category;
};
}])
/**
Store factory
*/
categorieFilter.factory('store', function($http, $q){
function _getCategory (){
var deferred = $q.defer();
$http.get('api/categories').success(function (data) {
deferred.resolve(data);
})
return deferred.promise;
}
function _getProducts (){
var deferred = $q.defer();
$http.get('api/products').success(function (data) {
deferred.resolve(data);
}
return deferred.promise;
}
return {
getCategories: _getCategory,
getProducts : _getProducts
};
});
I usually create services using $resource. You could try this:
categorieFilter = angular.module("categorieFilter", []);
categorieFilter.factory('categoryStore', [
'$resource',
function($resource) {
return $resource('/api/categories/', {}, {
getCategories: { method: 'GET', params: {} },
});
}
]);
categorieFilter.factory('productsStore', [
'$resource',
function ($resource) {
return $resource('/api/products/', {}, {
getProducts: { method: 'GET', params: {} },
});
}
]);
categorieFilter.controller("catFilter", [
"$scope", "categoryStore", "productsStore", function ($scope, categoryStore, productsStore) {
$scope.search = "";
$scope.products = [];
$scope.categories = [];
$scope.categories = categoryStore.getCategories();
$scope.products = productsStore.getProducts();
$scope.filterProductsByCats = function(category) {
$scope.search = category;
};
}
]);
I usually write http factories passing a callback function parameter (I usually work with Node and I'm used to do this for long working functions). Taking your code it will looks something like this:
categorieFilter = angular.module("categorieFilter", [])
categorieFilter.controller("catFilter", ["$scope", "store", function($scope, store){
$scope.search = "";
$scope.products = [];
$scope.categories = [];
store.getCategories(function(err, data){
if(!err)
$scope.categories = data;
});
store.getProducts(function(err, data){
if(!err)
$scope.products = data;
});
$scope.filterProductsByCats = function(category){
$scope.search = category;
};
}])
categorieFilter.factory('store', function($http){
return {
getCategories: function(next){
$http.get('api/categories')
.success(function (data) {
next(null, data);
})
.error(function(headers, status){
next(status, null);
});
},
getProducts : function(next){
$http.get('api/products')
.success(function (data) {
next(null, data);
})
.error(function(headers, status){
next(status, null);
});
}
};
});
As you can see now factory takes a callback that will be called with error and data parameters, so error handling can be delegate or not to the controller. This is pretty useful for complex situations.
Here's a plunker that works using $q and defer explicitly with some random JSON.
var app = angular.module('categorieFilter', []);
app.factory('store', function($http, $q){
return {
getCategories: function() {
var deferred = $q.defer();
$http.get('https://api.myjson.com/bins/2gamd')
.success(deferred.resolve)
.error(deferred.resolve);
return deferred.promise;
}
}
})
.controller('catFilter', function($scope, store){
store.getCategories().then(function(data) {
$scope.categories = data.stories;// change data.stories to whatever your data is
});
});
Related
I looked into examples on how to do this properly but it's definitely not updating on my end. I put a breakpoint to make sure it's updating and going through the timer in the Factory and it's updating properly. I shouldn't have to use $watch right? If someone can help me figure out what's going on it would help with my headache right now lol thanks.
Factory
app.factory('FoundationSystemStatusFactory', ['$timeout', '$q', 'SystemStatusFactory', function ($timeout, $q, SystemStatusFactory) {
var service = {};
service.Count = 0;
service.Ping = 0;
service.PollingTest = function() {
$timeout(function () {
SystemStatusFactory.PingIP('www.google.com')
.then(function (data) {
service.Ping = data.data;
service.Count++;
}, function (data) {
service.Ping = data.data;
});
service.PollingTest();
}, 2000);
}
return service;
}]);
Controller
FoundationSystemStatusFactory.PollingTest();
$scope.ping = FoundationSystemStatusFactory.Ping; //NOT UPDATING
$scope.count = FoundationSystemStatusFactory.Count; //NOT UPDATING
EDIT: tried as Service, still couldn't get it to work:
var self = this;
self.Count = 0;
self.Ping = 0;
self.PollingTest = function () {
$timeout(function () {
SystemStatusFactory.PingIP('www.google.com')
.then(function (data) {
self.Ping = data.data;
self.Count++;
}, function (data) {
self.Ping = data.data;
});
self.PollingTest();
}, 2000);
}
A different approach - events.
app.factory('FoundationSystemStatusFactory', ['$rootScope', '$timeout', '$q', 'SystemStatusFactory', function ($rootScope, $timeout, $q, SystemStatusFactory) {
var service = {
Count: 0
};
service.PollingTest = function() {
$timeout(function () {
SystemStatusFactory.PingIP('www.google.com')
.then(function (data) {
$rootScope.$broadcast('FoundationSystemStatus:ping', data.data);
service.Count++;
}).catch(function (data) {
$rootScope.$broadcast('FoundationSystemStatus:ping', data.data);
});
service.PollingTest();
}, 2000);
}
return service;
}]);
//On controller...
$scope.$on('FoundationSystemStatus:ping', function(ping){
$scope.ping = ping;
});
You can use watcher:
$scope.$watch('FoundationSystemStatusFactory.Ping', function(newValue) {
$scope.ping = newValue;
});
Or you can use reference to factory:
$scope.status = FoundationSystemStatusFactory;
$interval(function() {
console.log($scope.status.Ping); // gets updated
});
Okay I found out how to do it after some more research. Objects are referenced as numbers and strings are not.
Factory
app.factory('FoundationSystemStatusFactory', ['$timeout', '$q', 'SystemStatusFactory', function ($timeout, $q, SystemStatusFactory) {
var service = {};
service.Data = {
Count: 0,
Ping: 0
}
service.PollingTest = function() {
$timeout(function () {
SystemStatusFactory.PingIP('www.google.com')
.then(function (data) {
service.Data.Ping = data.data;
service.Data.Count++;
}, function (data) {
service.Data.Ping = data.data;
});
service.PollingTest();
}, 2000);
}
return service;
}]);
Controller
app.controller('SystemStatusController', ['$scope', '$rootScope', '$timeout', 'FoundationSystemStatusFactory',
function ($scope, $rootScope, $timeout, FoundationSystemStatusFactory) {
FoundationSystemStatusFactory.PollingTest();
$scope.data = FoundationSystemStatusFactory.Data;
}]);
View
{{data.Ping}}
{{data.Count}}
I have a function which updates the object, the problem is when I go back from the update form field to the detailed view, it initializes the old object instead of the updated object.
I want to populate the cars list in the CarService instead of the app.js
This is my carService:
window.app.service('CarService', ['HTTPService', '$q',
'$http', function (HTTPService, $q, $http) {
'use strict';
this.cars = [];
this.get = function () {
var deferred = $q.defer();
HTTPService.get('/car').then(function resolve(response) {
deferred.resolve(response.data);
}, function reject(response){
deferred.reject(response);
});
};
this.add = function (formCar) {
var deferred = $q.defer();
console.log("CarService response 1 : ");
$http.post('/#/car', formCar).then(function resolve(response){
deferred.resolve(response.data);
}, function reject(response){
deferred.reject(response);
});
return deferred.promise;
};
this.showDetails = function (carId){
var deferred = $q.defer();
$http.get('/car/view/{{carId}}').then(function resolve(response){
HTTPService.get('/car/view/' + carId).then(function
resolve(response) {
deferred.resolve(response.data);
}, function reject(response){
deferred.reject(response);
});
return deferred.promise;
};
this.put = function (carformUpdate, opleidingsprofielId) {
var deferred = $q.defer();
$http.put('/#/car/:carId/update', carformUpdate).then(function resolve(response){
deferred.resolve(response.data);
}, function reject(response){
deferred.reject(response);
});
return deferred.promise;
};
}]);
This is my updateCar controller:
window.app.controller('updateCarCtrl', ['$scope', '$routeParams',
'CarService', '$location', function ($scope, $routeParams, CarService,
$location) {
'use strict';
$scope.carId = $routeParams.carId;
initCar($scope.carId);
function initCar(carId) {
CarService.showDetails(carId).then(function success(car) {
$scope.car = car;
}, function error(response) {
});
}
$scope.updateCar = function (carId) {
carId = $scope.carId;
if($scope.car !== null){
CarService.put($scope.car, carId).then(function
success(response) {
$scope.car = response;
$location.path('/car/view/' + carId);
alert("Car updated");
}, function error(response) {
$scope.error = response.statusText;
$scope.myform = {};
});
}
};
}]);
This is my carView controller:
window.app.controller('carViewCtrl', ['$scope', '$routeParams', '$location',
'CarService', function ($scope, $routeParams, $location, CarService) {
'use strict';
$scope.carId = $routeParams.carId;
initCar($scope.carId);
function initCar(carId) {
CarService.showDetails(carId).then(function success(car) {
$scope.car = car;
}, function error(response) {
});
}
}]);
My carView initializes the object again when it gets redirected with $location.path('/car/view/' + carId); but as the original object and not the updated object.
I'm trying to do this on an ngMock backend.
My app.js looks like this:
App.js
routing:
.when('/car', {
templateUrl: 'pages/car/car.html'
})
.when('/car/view/:carId', {
templateUrl: 'pages/car/carView.html',
controller: 'carViewCtrl',
controllerAs: 'ctrl'
})
.when('/car/addCar', {
templateUrl: 'pages/car/carAdd.html'
})
.when('/car/:carId/update', {
templateUrl: 'pages/car/carUpdate.html',
controller: 'updateCarCtrl',
conrtollerAs: 'ctrl'
})
app.run: this is where my mock backend is defined
window.app.run(function($httpBackend) {
var cars = [
{
id: 0,
name: ‘car0’,
address: 'adress0',
tel: 'tel0',
email: 'email0'},
{
id: 1,
name: ‘car1’,
address: 'adress1',
tel: 'tel1',
email: 'email1'
}];
var carUrl = “/#/car”;
$httpBackend.whenGET(carUrl).respond(function(method,url,data) {
return [200, cars, {}];
});
$httpBackend.whenGET(/\/#\/car\/view\/(\d+)/, undefined,
['carId']).respond(function(method, url, data, headers, params) {
return [200, cars[Number(params.carId)], {
carId : params.carId
}];
});
$httpBackend.whenPUT('/#/car/:carId/update').respond(function(method, url,
data, carId) {
var car = angular.fromJson(data);
return [200, car, {}];
});
Thanks for any help!
It looks like your update function calls the CarService.put, which in turn calls a HTTPService.put. In your mocked backend you have this:
$httpBackend.whenPUT
-> add new car;
So it always adds a new car, and doesn't update one. This means that when you do the get, you probably get the first car back that matches the given id, which isn't the updated one.
In pseudo code:
// carService.cars = [{id:1,name:"name"}]
var myCar = carService.get(1); // returns {id:1,name:"name"}
myCar.name = "otherName";
carService.put(car); // -> cars.push(car); -> cars = [{id:1,name:"name"},{id:1,name:"otherName"}]
goToDetails(1);
var myCar = carService.get(1); // iterate over the cars, and return the one with id = 1,
// which is {id:1,name:"name"}
I have a function which updates the object, the problem is when I go back from the update form field to the detailed view, it initializes the old object instead of the updated object.
I want to populate the cars list in the CarService instead of the app.js
This is my carService:
window.app.service('CarService', ['HTTPService', '$q',
'$http', function (HTTPService, $q, $http) {
'use strict';
this.cars = [];
this.get = function () {
var deferred = $q.defer();
HTTPService.get('/car').then(function resolve(response) {
deferred.resolve(response.data);
}, function reject(response){
deferred.reject(response);
});
};
this.add = function (formCar) {
var deferred = $q.defer();
console.log("CarService response 1 : ");
$http.post('/#/car', formCar).then(function resolve(response){
deferred.resolve(response.data);
}, function reject(response){
deferred.reject(response);
});
return deferred.promise;
};
this.showDetails = function (carId){
var deferred = $q.defer();
$http.get('/car/view/{{carId}}').then(function resolve(response){
HTTPService.get('/car/view/' + carId).then(function
resolve(response) {
deferred.resolve(response.data);
}, function reject(response){
deferred.reject(response);
});
return deferred.promise;
};
this.put = function (carformUpdate, opleidingsprofielId) {
var deferred = $q.defer();
$http.put('/#/car/:carId/update', carformUpdate).then(function resolve(response){
deferred.resolve(response.data);
}, function reject(response){
deferred.reject(response);
});
return deferred.promise;
};
}]);
This is my updateCar controller:
window.app.controller('updateCarCtrl', ['$scope', '$routeParams',
'CarService', '$location', function ($scope, $routeParams, CarService,
$location) {
'use strict';
$scope.carId = $routeParams.carId;
initCar($scope.carId);
function initCar(carId) {
CarService.showDetails(carId).then(function success(car) {
$scope.car = car;
}, function error(response) {
});
}
$scope.updateCar = function (carId) {
carId = $scope.carId;
if($scope.car !== null){
CarService.put($scope.car, carId).then(function
success(response) {
$scope.car = response;
$location.path('/car/view/' + carId);
alert("Car updated");
}, function error(response) {
$scope.error = response.statusText;
$scope.myform = {};
});
}
};
}]);
This is my carView controller:
window.app.controller('carViewCtrl', ['$scope', '$routeParams', '$location',
'CarService', function ($scope, $routeParams, $location, CarService) {
'use strict';
$scope.carId = $routeParams.carId;
initCar($scope.carId);
function initCar(carId) {
CarService.showDetails(carId).then(function success(car) {
$scope.car = car;
}, function error(response) {
});
}
}]);
My carView initializes the object again when it gets redirected with $location.path('/car/view/' + carId); but as the original object and not the updated object.
I'm trying to do this on an ngMock backend.
My app.js looks like this:
App.js
routing:
.when('/car', {
templateUrl: 'pages/car/car.html'
})
.when('/car/view/:carId', {
templateUrl: 'pages/car/carView.html',
controller: 'carViewCtrl',
controllerAs: 'ctrl'
})
.when('/car/addCar', {
templateUrl: 'pages/car/carAdd.html'
})
.when('/car/:carId/update', {
templateUrl: 'pages/car/carUpdate.html',
controller: 'updateCarCtrl',
conrtollerAs: 'ctrl'
})
app.run: this is where my mock backend is defined
window.app.run(function($httpBackend) {
var cars = [
{
id: 0,
name: ‘car0’,
address: 'adress0',
tel: 'tel0',
email: 'email0'},
{
id: 1,
name: ‘car1’,
address: 'adress1',
tel: 'tel1',
email: 'email1'
}];
var carUrl = “/#/car”;
$httpBackend.whenGET(carUrl).respond(function(method,url,data) {
return [200, cars, {}];
});
$httpBackend.whenGET(/\/#\/car\/view\/(\d+)/, undefined,
['carId']).respond(function(method, url, data, headers, params) {
return [200, cars[Number(params.carId)], {
carId : params.carId
}];
});
$httpBackend.whenPUT('/#/car/:carId/update').respond(function(method, url,
data, carId) {
var car = angular.fromJson(data);
return [200, car, {}];
});
Thanks for any help!
It looks like your update function calls the CarService.put, which in turn calls a HTTPService.put. In your mocked backend you have this:
$httpBackend.whenPUT
-> add new car;
So it always adds a new car, and doesn't update one. This means that when you do the get, you probably get the first car back that matches the given id, which isn't the updated one.
In pseudo code:
// carService.cars = [{id:1,name:"name"}]
var myCar = carService.get(1); // returns {id:1,name:"name"}
myCar.name = "otherName";
carService.put(car); // -> cars.push(car); -> cars = [{id:1,name:"name"},{id:1,name:"otherName"}]
goToDetails(1);
var myCar = carService.get(1); // iterate over the cars, and return the one with id = 1,
// which is {id:1,name:"name"}
I have this in the controller
angular.module('myApp')
.controller('TaskController', function ($scope, TaskFactory) {
$scope.addTodo = function () {
$scope.todos.push({text : $scope.formTodoText});
$scope.formTodoText = '';
};
});
and this in the factory
angular.module('myApp')
.factory('TaskFactory', function ($q, $http) {
var sendTasks = function(params) {
var defer = $q.defer();
console.log(1, params);
$http.post('http://localhost:3000/task/save', params)
.success(function(data) {
console.log(2);
console.log('data', data);
})
.error(function(err) {
defer.reject(err);
});
return defer.promise;
}
return {
sendTask: function(taskData) {
console.log('taskData', taskData);
return sendTasks('/task/save', {
taskData : taskData
})
}
}
});
all I need is to know, how to send the data from the controller to the factory in order to do the POST to the specified route ?
You just need to call the function/method inside factory with the required params.
angular.module('myApp')
.controller('TaskController', function ($scope, TaskFactory) {
$scope.addTodo = function () {
$scope.todos.push({text : $scope.formTodoText});
TaskFactory.sendTask({data : $scope.formTodoText})
$scope.formTodoText = '';
};
});
You can follow Dan Wahlin blog post.
Controller:
angular.module('customersApp')
.controller('customersController', ['$scope', 'dataFactory', function ($scope, dataFactory) {
$scope.status;
dataFactory.updateCustomer(cust)
.success(function () {
$scope.status = 'Updated Customer! Refreshing customer list.';
})
.error(function (error) {
$scope.status = 'Unable to update customer: ' + error.message;
});
}
Factory:
angular.module('customersApp')
.factory('dataFactory', ['$http', function($http) {
var urlBase = '/api/customers';
dataFactory.updateCustomer = function (cust) {
return $http.put(urlBase + '/' + cust.ID, cust)
};
}
Hope that solve your problem.
You can call the function directly on the TaskFactory that you pass into the controller as a dependency.
I've cleaned up your code a bit and created a plunk for you here:
And here's the code:
Controller
(function(angular) {
// Initialise our app
angular.module('myApp', [])
.controller('TaskController', function($scope, TaskFactory) {
// Initialise our variables
$scope.todos = [];
$scope.formTodoText = '';
$scope.addTodo = function() {
// Add an object to our array with a 'text' property
$scope.todos.push({
text: $scope.formTodoText
});
// Clear the input
$scope.formTodoText = '';
// Call function to send all tasks to our endpoint
$scope.sendTodos = function(){
TaskFactory.sendTasks($scope.todos);
}
};
});
})(angular);
Factory
(function(angular) {
angular.module('myApp')
.factory('TaskFactory', function($q, $http) {
var sendTasks = function(params) {
var defer = $q.defer();
$http.post('http://localhost:3000/task/save', params)
.success(function(data) {
console.log('data: ' + data);
})
.error(function(err) {
defer.reject(err);
});
return defer.promise;
}
return {
sendTasks: sendTasks
}
});
})(angular);
I am trying to create an Angular Factory, this is based on a example from a plural site course http://www.pluralsight.com/training/player?author=shawn-wildermuth&name=site-building-m7&mode=live&clip=3&course=site-building-bootstrap-angularjs-ef-azure.
From debugging the code in Chrome it appears to run fine. I can see when I debug it that the service gets my data and puts it in my array but when I look at the controller in either $scope.data or dataService.data the arrays are empty. I don't see any javascript errors. I'm not sure what I'm doing wrong, any suggestions. I'm using AngularJS v1.3.15.
module.factory("dataService", function($http,$routeParams,$q) {
var _data = [];
var _getData = function () {
var deferred = $q.defer();
$http.get("/api/v1/myAPI?mainType=" + $routeParams.mainType + "&subType=" + $routeParams.subType)
.then(function (result) {
angular.copy(result.data,_data);
deferred.resolve();
},
function () {
//Error
deferred.reject();
});
return deferred.promise;
};
return {
data: _data,
getData: _getData
};});
module.controller('dataController', ['$scope', '$http', '$routeParams', 'dataService',function ($scope, $http, $routeParams, dataService) {
$scope.data = dataService;
$scope.dataReturned = true;
$scope.isBusy = true;
dataService.getData().then(function () {
if (dataService.data == 0)
$scope.dataReturned = false;
},
function () {
//Error
alert("could not load data");
})
.then(function () {
$scope.isBusy = false;
})}]);
On
return {
data: _data,
getData: _getData
};});
you have "data: _data," while your array is named just "data". Change the name of the variable to match and it will work:
var _data = [];
Why would you use deferred from $q this way?
The proper way to use $q:
$http.get("/api/v1/myAPI?mainType=" + $routeParams.mainType + "&subType=" + $routeParams.subType)
.success(function (result) {
deferred.resolve(result);
}).error(
function () {
//Error
deferred.reject();
});
And then in controller
dataService
.getData()
.then(function success(result) {
$scope.data = result; //assing retrived data to scope variable
},
function error() {
//Error
alert("could not load data");
});
In fact, there are some errors in your codes :
In your Service, you define var data = [];, but you return data: _data,. So you should correct the defination to var _data = []
you don't define _bling, but you use angular.copy(result.data,_bling);
One more question, why do you assigne the service to $scope.data : $scope.data = dataService ?
EDIT :
Notice that there 3 changes in the following codes:
comment the $scope.data = dataService;, because it makes no sense, and I think that $scope.data should be the data that the service returns.
$scope.data = dataService.data;, as I described in 1st point. You can see the result from the console.
In the if condition, I think that you want to compare the length of the returned data array, but not the data.
module.controller('dataController', ['$scope', '$http', '$routeParams', 'dataService',function ($scope, $http, $routeParams, dataService) {
// $scope.data = dataService;
$scope.dataReturned = true;
$scope.isBusy = true;
dataService.getData().then(function () {
if (dataService.data.length === 0){
$scope.dataReturned = false;
}else{
$scope.data = dataService.data;
console.log($scope.data);
}
},
// other codes...
})}]);