使用AngularJS在两个不同的指令中调用相同的$http.get()

Call the same $http.get() in 2 different directives using AngularJS

本文关键字:调用 get http 指令 AngularJS 两个 使用      更新时间:2023-09-26

我正在使用AngularJS和D3.JS

我有一个html表单如下:

    <div simple-chart chart-data="lineData"></div>

这是连接到一个指令,像这样:

mist.directive("simpleChart", function($window, $http){
    return{
        restrict: "EA",
        template: "<svg width='750' height='200'></svg>",
        link: function(scope, elem, attrs){
            function drawLineChart() {
                //initilize the line chart
            }
            $http.get("myurl")
            .success(function(data, status, headers, config){
                drawLineChart();
            })
        }}
  });
  1. 是否有可能使用$http.get("myurl")的数据创建另一个指令,而不必再次调用它?
  2. 是否有可能使$http.get("myurl")通用,以便它可以被不同的指令调用?
  3. 我可以用这样的东西吗?无法从jQuery Ajax调用中获得正确的返回值

你可以把你的http调用包装成一个服务,并使用类似angular-cache的东西来缓存来自服务器的响应。

你可以创建一个返回$http.get('myurl')的服务,并把它作为一个依赖项添加到你的指令中。

mist.factory('dataService', function ($http) {
    var dataService= {};
    dataService.getData = function(){
       return $http.get('myurl');
    }
    return dataService;
});
mist.directive("simpleChart", function($window, dataService){
return{
    restrict: "EA",
    template: "<svg width='750' height='200'></svg>",
    link: function(scope, elem, attrs){
        function drawLineChart() {
            //initilize the line chart
        }
        dataService.getData()
        .success(function(data, status, headers, config){
            drawLineChart();
        })
    }}
});

因为我使用的是AngularJS1.3,所以我需要使用

            mist.factory('dataService', function ($http) {
            return {
                getData: function () {
                    //since $http.get returns a promise,
                    //and promise.then() also returns a promise
                    //that resolves to whatever value is returned in it's
                    //callback argument, we can return that.
                    return $http.get('http://url.com').then(function (result) {
                        return result.data;
                    });
                }
            };
        });
        mist.directive("simpleChart", function ($window, dataService) {
            return{
                restrict: "EA",
                template: "<svg width='750' height='200'></svg>",
                link: function (scope, elem, attrs) {
                    function drawLineChart() {
                        //initilize the line chart
                    }
                    dataService.getData().then(
                            function (data) {
                                drawLineChart();
                            },
                            function (err) {
                                console.log("Sorry we encountered an error " + err);
                            }
                    );
                }};
        });

来源:http://www.benlesh.com/2013/02/angularjs-creating-service-with-http.html