当异步调用正在处理时,AngularJS仅更新一次

时间:2016-05-08 20:56:11

标签: angularjs

我可以通过控制器播种数据,例如:

https://jsfiddle.net/0nbu1uaL/2/

var myApp = angular.module('myApp',[]);

myApp.factory('myService', function($timeout) {
        var _myValue = null;
    return {
            value: function() {
            // May be called more than once
            return _myValue;
        },
        UpdateValue: function() {
            $timeout(function() {
                _myValue = "Hello World!"
            }, 3000);
        }
    };
});

myApp.controller('MyCtrl', function($scope, myService) {
    $scope.value = myService.value;
    myService.UpdateValue();
});

但我希望我的服务知道何时根据条件填充本地数据,例如:

https://jsfiddle.net/q783gjor/2/

var myApp = angular.module('myApp',[]);

myApp.factory('myService', function($timeout) {
        var _isUpdating = false;
        var _myValue = null;
    myService = {};
     myService.UpdateValue = function() {
              _isUpdating = true;
            $timeout(function() {
                console.log('processed timeout')
                _myValue = "Hello World!"
                _isUpdating = false;
            }, 3000);
        };
     myService.value = function() {
            // May be called more than once
            if (_myValue == null && _isUpdating == false) {
                  myService.UpdateValue();
            }
            console.log('value() called')
            return _myValue;
        };

    return myService;
});

myApp.controller('MyCtrl', function($scope, myService) {
    $scope.value = myService.value;
});

是否有一种方法可以在不保留本地'isUpdating'变量来跟踪状态的情况下进行第二种方法?由于value()被多次调用,我需要一个只调用一次(一次)的UpdateValue()的干净方法

0 个答案:

没有答案