Alice Xu
Alice Xu

Reputation: 543

angularjs service doesn't work in my case

Below is an element is within my mainController

<img src="loader.gif" ng-hide="done_ajax"/>

and my js look like this

//service
    app.service('request_service', function(){
        this.finished = false;
    });

//main ctonroller
    app.controller('mainController', ['$scope','request_service', function($scope,request_service){
            $scope.ajaxed = request_service.finished;
    }]);

// second controller
app.controller('secondController', ['$scope','request_service', function($scope,request_service){

    callAPI("getUser", {
                method: "GET"
            }).success(function (resp) {

                $scope.$apply(function () {
                 request_service.finished = true;
           });

    });

What's wrong is my usage of angularjs service? I want to hide a loader that controlled by the mainController, by passing the conditional value when the ajax call is done in my second controller.

Upvotes: 0

Views: 75

Answers (1)

skubski
skubski

Reputation: 1606

You request a value of your service and you do not watch it for changes. Therefore it will most likely (depending on the sequence and time your controllers are initialized) be false and remain false.

$scope.ajaxed = request_service.finished;

If you want to know when the request_service.finished changes, it should be watched:

$scope.isFinished = aService.isFinished;

$scope.$watch(function() { return aService.isFinished; }, function(newV, oldV) {
    $scope.isFinished = newV;
});

Upvotes: 1

Related Questions