编程语言
首页 > 编程语言> > javascript-如何在AngularJS中异步填充$scope变量?

javascript-如何在AngularJS中异步填充$scope变量?

作者:互联网

我有以下服务:

app.service('Library', ['$http', function($http) {

    this.fonts = [];
    this.families = [];

    // ... some common CRUD functions here ...

    // Returns the font list
    this.getFonts = function() {
        if(_.isEmpty(this.fonts)) this.updateFonts();
        return this.fonts;
    };

    // Returns the family list
    this.getFamilies = function() {
        if(_.isEmpty(this.families)) this.updateFamilies();
        return this.families;
    };

    // Update the font list
    this.updateFonts = function() {
        var self = this;
        $http.get(BACKEND_URL+'/fonts').success(function(data) {
            self.fonts = data;
            console.log('Library:: fonts updated', self.fonts);
        });
    };

    // Update the family
    this.updateFamilies = function() {
        var self = this;
        $http.get(BACKEND_URL+'/families').success(function(data) {
            var sorted = _.sortBy(data, function(item) { return item });
            self.families = sorted;
            console.log('Library:: families updated', self.families);
        });
    };
}]);

以及以下主控制器代码:

app.controller('MainController', ['$scope', '$state', 'Cart', 'Library', function($scope, $state, Cart, Library) {
    console.log('-> MainController');

    // Serve the right font list depending on the page
    $scope.fonts = $state.is('home.cart') ? Cart.getFonts() : Library.getFonts();
    $scope.families = Library.getFamilies();

}]);

问题是,当视图请求$scope.fonts的内容时,它仍然为空.

加载结束后如何更新$scope.fonts和$scope.families?

我可以使用$scope.$watch,但是我敢肯定有一种更干净的方法来做…

解决方法:

这确实是promises的用途.您的服务应返回将要解决的承诺.您还可以简化服务:

app.service('Library', ['$http', '$q', function($http, $q) {
    var self = this;

    self.families = [];

    // Returns the family list
    self.getFamilies = function() {
        var deferred = $q.defer();

        if(_.isEmpty(self.families)) {
            $http.get(BACKEND_URL+'/families').success(function(data) {
                var sorted = _.sortBy(data, function(item) { return item });
                self.families = sorted;
                deferred.resolve(self.families);
                console.log('Library:: families updated', self.families);
            });
        } else {
            deferred.resolve(self.families);
        }

        return deferred.promise;
    };
}]);

然后在您的控制器中,使用promise then方法:

app.controller('MainController', ['$scope', '$state', 'Cart', 'Library', function($scope, $state, Cart, Library) {
    console.log('-> MainController');

    // Serve the right font list depending on the page
    $scope.fonts = $state.is('home.cart') ? Cart.getFonts() : Library.getFonts();
    Library.getFamilies().then(function(result) {
        $scope.families = result;
    });
}]);

由于$http,未经测试,但这是使用$timeout的演示:

JSFiddle

标签:angularjs,asynchronous,angularjs-scope,angularjs-service,javascript
来源: https://codeday.me/bug/20191028/1951721.html