简体   繁体   中英

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.

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;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM