trubliphone trubliphone - 2 months ago 17
AngularJS Question

Access angularjs services from a controller

I have added some code to block user interaction while angular $http requests are in-progress:

controller.js:

var app = angular.module("my_app", ["my_app"]);
app.controller("MyController", ['$scope', '$http', function($scope, $http) {
$scope.blocking = false;
$scope.do_something = function() {
$scope.blocking = true;
$http({
method: "POST",
url: "some.url.com",
data: my_data
}).success(function(data) {
// do something nice
}).error(function(data) {
// do some error handling
}).finally(function() {
$scope.blocking = false;
});
};
}]);


template.html:

<div ng-controller="MyController">
<fieldset ng-disabled="blocking">
<form>
...a bunch of form elements...
...including a "submit" button...
...some of which call "do_something" above...
</form>
</fieldset>
</div>


When I run the "do_something" fn this correctly sets "blocking" to true which has the effect of preventing all user interaction inside the fieldset. Hooray.

However, my code needs to do this sort of thing a lot. So I tried to move the functionality to a service:

service.js:

app.factory('$my_service', ['$http', function($http) {
_blocking = false;
return {
getBlocking: function() {
return _blocking;
},
setBlocking: function(blocking) {
_blocking = blocking;
}
}
}]);


Then my "do_something" fn above simply calls $my_service.setBlocking as needed. However, I don't know what to put for the argument of ng-disabled.

Any suggestions?




As requested by @user449689, here is the new controller code:

app.controller("MyController", ['$scope', '$http', '$my_service', function($scope, $http, $my_service) {
$scope.do_something = function() {
$my_service.setBlocking(true);
$http({
method: "POST",
url: "some.url.com",
data: my_data
}).success(function(data) {
// do something nice
}).error(function(data) {
// do some error handling
}).finally(function() {
$my_service.setBlocking(false);
});
};
}]);


But I can't figure out what to put in the "ng-disabled" attribute of the fieldset element.

Answer

Just update your $scope.blocking on the controller to reference the service method $my_service.getBlocking and update the HTML to

<fieldset ng-disabled="blocking()">

On controller

$scope.blocking = $my_service.getBlocking
Comments