Angular.js在指令之间共享服务数据

时间:2022-09-10 12:09:34

I'm working on my first Angular.js application and I'm a bit confused. Currently I have two directives that both need the same data to build up the page. This data is loaded from an external api.

我正在研究我的第一个Angular.js应用程序,我有点困惑。目前我有两个指令,它们都需要相同的数据来构建页面。此数据从外部api加载。

Now currently I have created this factory, which looks like:

现在我已经创建了这个工厂,看起来像:

(function() {
    var app = angular.module('dataService', []);
    app.factory('dataService', ['$http', function($http) {
        var links = [];

        return {
            getMenu: function() {
                if(links.length > 0) {
                    return links;
                } else {
                    $http.get('http://localhost/server/api.php?ajax=true&action=getCats').success(function(data) {
                        return data;
                    })
                }
            }
        }
    }])
})();

But I'm rather confused how to use this service, obviously if there is a $http request, the return will never be called with the correct data.

但是我很担心如何使用这个服务,显然如果有一个$ http请求,将永远不会使用正确的数据调用返回。

In my directive I would use it like this:

在我的指令中,我会像这样使用它:

(function() {
    // Menu directive
    var app = angular.module('menu', ['dataService']);
    app.directive('menu', ['dataService', function(dataService) {
        return {
            restrict: 'E',
            templateUrl: 'scripts/menu/menu.html',
            controller: function() {
                console.log(dataService.getMenu()); // Return 'undefined'
            },
            controllerAs: 'menuCtrl'
        }
    }])
})();

1 个解决方案

#1


2  

Change your service method so that it handles both synchronous and asynchronous scenarios:

更改服务方法,以便它处理同步和异步方案:

  getMenu: function() {
                 var deferred = $q.defer();
                if(links.length > 0) {
                   deferred.resolve(links);
                } else {
                    $http.get('http://localhost/server/api.php?ajax=true&action=getCats').success(function(data) {
                   deferred.resolve(data);
                    })
                }
           return deferred.promise;
   }

Usage:

dataService.getMenu().then(function(data){
  console.log(data);
});

#1


2  

Change your service method so that it handles both synchronous and asynchronous scenarios:

更改服务方法,以便它处理同步和异步方案:

  getMenu: function() {
                 var deferred = $q.defer();
                if(links.length > 0) {
                   deferred.resolve(links);
                } else {
                    $http.get('http://localhost/server/api.php?ajax=true&action=getCats').success(function(data) {
                   deferred.resolve(data);
                    })
                }
           return deferred.promise;
   }

Usage:

dataService.getMenu().then(function(data){
  console.log(data);
});