0

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.

1
  • create a plunker plz Commented Aug 31, 2015 at 13:09

1 Answer 1

1

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;
});
Sign up to request clarification or add additional context in comments.

13 Comments

why there's param in the $watch callback? can't I just set $scope.ajaxed = false? but either with that it doesn't work. Strange.
It's a listener function defined in the docs, you can click on the link I supplied to read up on the $watch method. Yes, it should be in your main controller.
strange it doesn't work still, anything wrong for my service? and my second controller?
when I console.log(newVal, oldVal) it return undefined.
I think you should change your $watch variable into $scope.$watch(function(){ return request_service.finished} .... Working fiddle
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.