Skip to content

Instantly share code, notes, and snippets.

@Deraen
Last active August 29, 2015 13:57
Show Gist options
  • Select an option

  • Save Deraen/9811452 to your computer and use it in GitHub Desktop.

Select an option

Save Deraen/9811452 to your computer and use it in GitHub Desktop.
angular-utils.js
angular.module('fooApp')
.factory('Util', function() {
var utils = {};
// Would be passed by value if $scope.foo was given directly.
// As scope is object it is passed by reference.
utils.Pending = function(scope, target) {
scope[target] = false;
this.start = function() {
scope[target] = true;
};
this.stop = function() {
scope[target] = false;
};
};
utils.Error = function(scope, target) {
scope[target] = null;
this.clear = function() {
scope[target] = null;
};
this.set = function(err) {
scope[target] = err;
};
};
return utils;
});
<button class="btn btn-success" ng-click="doFoo()" ng-class="{'spinner-active': fooPending}">
<span class="spinner glyphicon glyphicon-save"></span> Foo
</button>
<div error="fooError"></div>
angular.module('fooApp')
.controller(function($scope, $http, Util) {
var error = new Util.Error($scope, 'fooError');
var pending = new Util.Pending($scope, 'fooPending');
$scope.doFoo = function() {
error.clear();
pending.start();
$http.get('/foo').success(function(data) { ... }).error(error.set).finally(pending.stop);
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment