Simple AngularJS Service Example
HTML
<div ng-controller="SimpleCtrl">
<strong>Todos {{todos.length}}</strong> Get todos: <button ng-click="getTodos()">via data-binding</button> <button ng-click="getTodoViaPromise()">or via a promise</button><br/> (reload to try a different button)
<ul>
<li ng-repeat="todo in todos">{{todo.text}}</li>
<li ng-show="todos.isLoading"><img src="https://www.bestwestern.com/img/ajaxSpinner.gif"/></li>
</ul>
</div>
JavaScript
angular.module('ServiceExample', []);
function SimpleCtrl(todoPromisedService, todoService, $scope) {
$scope.todos = todoService.todos;
$console.log($scope.todos);
$scope.getTodos = todoService.getTodos;
$scope.getTodoViaPromise = function() {
$scope.todos.isLoading = true;
todoPromisedService.getTodos()
.then(function(todos) {
$scope.todos = todos;
$scope.todos.isLoading = false;
}, function(error) {
alert(error); // never do this
});
};
}
angular.module('ServiceExample')
.value('config', {root: 'http://arcane-sierra-4822.herokuapp.com'})
.service('todoService', ['config', '$http', function(config, $http) {
var self = { todos: [] };
self.getTodos = function() {
self.todos.isLoading = true;
$http.get(config.root + '/todos')
.success(function(todos) {
console.log('Data retrieved');
self.todos.push.apply(self.todos, todos);
self.todos.isLoading = false;
})
.error(function() {
alert('failed, doh!'); //Never do this in the real world
});
};
return self;
}])
.service('todoPromisedService', ['config', '$http', '$q', function(config, $http, $q) {
this.getTodos = function() {
var deferred = $q.defer();
$http.get(config.root + '/todos')
.success(function(todos) {
deferred.resolve(todos);
})
.error(function() {
deferred.reject('oh shit!');
});
return deferred.promise;
};
}]);