javascript - Architecture of single method for ajax in Angularjs -
i'd understand how can design single ajax-method several controllers, can influence on user interface ('loading' animation, example).
idea (without promises):
var myapp = angular.module('myapp', []); myapp.controller('myctrl', function myctrl($scope, myfactory){ $scope.loading = false; $scope.somestuff = myfactory.getstuff(params); }); myapp.factory('myfactory', function(myservice){ return{ getstuff: function(params){ return myservice.ajax(params); } } }); myapp.service('myservice', function($http) { this.ajax = function(params){ // switch $scope.loading = true; // make request // return $http result // switch $scope.loading = false; }; });
as know, need use $scope ui changes , ajax-method should taken out custom service. services in angularjs not work $scope , have no idea how can solve problem.
i think, there must service chain of promises. how can designed?
upd: hope, time documentation more complete , clear. community of angular users great. thanks.
in project have defined service called appstate
has (among other) methods: showglobalspinner
, hideglobalspinner
modify variable on $rootscope
.
basically:
(…) .factory('appstate', ['$rootscope', function ($rootscope) { return { showglobalspinner: function () { ++$rootscope.loadinginprogress; }, hideglobalspinner: function () { if ($rootscope.loadinginprogress > 0) { --$rootscope.loadinginprogress } } }; }]);
what next show spinners wherever need them using ng-show
directive:
<div class="spinner" ng-show="loadinginprogress"></div>
before each ajax call appstate.showglobalspinner()
, after success/error call appstate.hideglobalspinner()
Comments
Post a Comment