I have create my own LoggerService but if I use it I get error:
FOrder.query is not a function
If i remove all LoggerService calls in controller all work fine, why i can't use LoggerService?
services.js
angular.module('GSAdmin.services', ['ngResource'])
.factory('FOrder', ['$resource', function($resource) {
return $resource('/api/order/:orderId');
}])
.service('LoggerService', [function(){
var _logList = [];
this.getLast = function(){
return _logList[_logList.length-1];
};
this.getLog = function(){
return _logList;
};
this.log = function(text) {
_logList.push(text);
};
}])
controller.js
.controller('OrderController', ['$scope', 'FOrder', 'LoggerService',
function($scope, FOrder, LoggerService) {
FOrder.query(function(data){
$scope.orders = data;
});
$scope.log = LoggerService.getLog();
LoggerService.log('Begin editing order #' + field.id);
}]);
.controller('OrderController', ['$scope', 'FOrder', 'LoggerService', function($scope, FOrder, LoggerService) {
FOrder.query(function(data){
$scope.orders = data;
});
$scope.log = LoggerService.getLog();
LoggerService.log('Begin editing order #' + field.id);
} <-- **you missed that bracket**
]);
Problem was in 'FOrder', 'LoggerService', i dont know why is important, but when i switch it to 'LoggerService', 'FOrder', all fine work.
Related
The URL I use to retreive a JSON for my app has a dynamic parameter (:id ). I'm not too sure how I can work with this, so that it passes the ID the user has chosen. Just need a bit of guidance.
app.factory('bookcategories', ['$http', function($http) {
return $http.get('http://52.41.65.211:8028/api/v1/categories/:id/books.json')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
Controller
app.controller('BookCategoryController', ['$scope', 'categories', '$routeParams', function($scope, categories, $routeParams) {
categories.success(function(data) {
$scope.detail = data.categories[$routeParams.bookId];
$scope.currentCategoryIndex = parseInt($routeParams.categoryId);
$scope.myCategoriesDetails = $scope.category;
});
}]);
app.js
...
.when('/categories/:categoryId', {
controller: 'BookCategoryController',
templateUrl: 'views/booksincategory.html'
})
...
HTML
<h3 class="title">{{book.title}}</h3>
You could achieve this with a little service like the following code example. A factory is a wrong choice here.
app.service('bookCategories', ['$http', function($http) {
this.get = function (id) {
return $http.get('http://52.41.65.211:8028/api/v1/categories/'+ id + '/books.json')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
};
}]);
And than use it like:
app.controller('MyCtrl', function(bookCategories) {
bookCategories.get(1).then(function (result) {
console.log(result);
});
});
Why in this code -> JSON get with angular and PHP , the service return an empty array but if i write:
angular.module('pageModule')
.factory('pageService', function($http){
var pagesArray = new Array();
return{
pagesArray: pagesArray,
load: function(){
$http.get('../angCMS/server/php/page.php')
.success(function(res){
pagesArray.push(res);
});
}
};
});
Controller:
angular.module('pageModule')
.controller('pageController', ['$scope', 'homeService', 'pageService', function($scope, homeService, pageService){
$scope.pages = pageService.pagesArray;
pageService.load();
}]);
everything works great?
Why are you not waiting for the call to be made. Make use of the promise that the $http is returning.
Factory:
// Original
angular.module('pageModule')
.factory('pageService', function($http){
var pagesArray = new Array();
return{
pagesArray: pagesArray,
load: function(){
$http.get('../angCMS/server/php/page.php')
// Success is deprecated use then and catch
.success(function(res){
pagesArray.push(res);
});
}
};
});
// Changed
angular.module('pageModule')
.factory('pageService', function($http){
var pagesArray = new Array();
return{
pagesArray: pagesArray,
load: function(){
return $http.get('../angCMS/server/php/page.php')
.then(function(res){
pagesArray.push(res);
return pagesArray;
});
}
};
});
Controller:
//Original
angular.module('pageModule')
.controller('pageController', ['$scope', 'homeService', 'pageService', function($scope, homeService, pageService){
$scope.pages = pageService.pagesArray;
pageService.load();
}]);
//Changed
angular.module('pageModule')
.controller('pageController', ['$scope', 'homeService', 'pageService', function($scope, homeService, pageService){
$scope.pages = [] //Initiale state;
//Make use of the HTTP promise that is returned in the load
pageService.load()
.then(function (pages) {
$scope.pages = pages;
})
.catch(function (error) {
//Handle error
console.log(error);
});
}]);
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 can't figure out how to destroy my cache to get a new list from my server.
When I get the first list, it's work perfect, but after inserting informations to my database and sending another get to my server, the browser only show the cached version of my list, without the new data.
I tried to use cacheFactory like this:
$cacheFactory.get('$http').removeAll();
but it doesn't worked.
Here is my angular Module, Service and Controller.
Module myApp
var app = angular.module('myApp', ['ngRoute', 'LocalStorageModule', 'angular-loading-bar', 'smart-table']);
app.config(function ($routeProvider) {
$routeProvider.when("/home", {
controller: "homeController",
templateUrl: "/web/views/home.html"
});
$routeProvider.when("/cidades", {
controller: "cidadesController",
templateUrl: "/web/views/basico/cidades/cidades.html"
});
$routeProvider.otherwise({ redirectTo: "/home" });
});
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptorService');
});
app.run(['authService', function (authService) {
authService.fillAuthData();
}]);
cidadesService
'use strict';
app.factory('cidadesService', ['$http', '$cacheFactory', function ($http, $cacheFactory) {
var serviceBase = 'http://localhost:22207/';
var serviceFactory = {};
var _getCidades = function () {
$cacheFactory.get('$http').removeAll(); //This doesn't worked
return $http.get(serviceBase + 'api/cidades/getall').then(function (results) {
return results;
});
};
serviceFactory.getCidades = _getCidades;
return serviceFactory;
}]);
cidadesController
'use strict';
app.controller('cidadesController', ['$scope', 'cidadesService', function ($scope, service) {
$scope.cidade = {
id: "",
nome:"",
};
$scope.message = "";
$scope.getCidades = function () {
service.getCidades().then(function (results) {
$scope.cidades = [];
$scope.collection = [];
$scope.cidades = results.data;
$scope.collection = [].concat($scope.cidades);
}, function (err) {
$scope.message = err.error_description;
});
};
//Initializing the list
$scope.getCidades();
}]);
I really don't see anything wrong, but in any case you can add unique param for your request to prevent caching
like
$http.get(serviceBase + 'api/cidades/getall?unique=' + new Date().getTime())
Unknown provider: $confirmModalProvider <- $confirmModal <- confirmModalCtrl
Why am I getting this error? I'm trying to use AngularJS UI Bootstrap to open a modal and get the result. I get this error when I trigger $scope.deleteQuestion(). Any idea what I'd doing wrong here?
var crtPromoCtrl = angular.module('crtPromoCtrl', ['crtPromoSrv']);
crtPromoCtrl.controller('surveyCtrl', ['$scope', '$modal', 'surveySrv', function($scope, $modal, surveySrv)
{
$scope.questions = surveySrv.getQuestions();
$scope.editQuestion = function(index)
{
surveySrv.setEditQuestion(index);
};
$scope.deleteQuestion = function(index)
{
var confirmModal = $modal.open({
templateUrl: 'confirm-delete.html',
controller: 'confirmModalCtrl',
size: 'sm'
});
confirmModal.result.then(function(msg)
{
console.log(msg);
});
return false;
};
}]);
crtPromoCtrl.controller('confirmModalCtrl', ['$scope', '$confirmModal', function($scope, $confirmModal)
{
$scope.yes = function()
{
$confirmModal.close('yes');
};
$scope.no = function()
{
$confirmModal.dismiss('no');
};
}]);
EDIT: https://angular-ui.github.io/bootstrap/#/modal
You second controller should use $modalInstance instead of $confirmModal
Please note that $modalInstance represents a modal window (instance)
dependency.
Code
crtPromoCtrl.controller('confirmModalCtrl', ['$scope', '$modalInstance', function($scope, $modalInstance) {
$scope.yes = function() {
$modalInstance.close('yes');
};
$scope.no = function() {
$modalInstance.dismiss('no');
};
}]);