角指令处理HTTP请求 [英] angular directive handles http request

查看:131
本文介绍了角指令处理HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有接受URL来获得远程数据角度指令:

I have angular directive that accept url to obtain remote data:

<my-tag src="http://127.0.0.1/srv1">...

指令本身:

app.directive('myTag', ['$http', function($http) {
return {
    restrict: 'E',
    transclude: true,
    replace: true,  
    //template: '<div ng-repeat="imgres in gallery">{{imgres.isUrl}}\'/></div>',
    scope:{
        src:"@",            //source AJAX url to dir pictures
    },
    controller:function($scope){
        console.info("enter directive controller");
        $scope.gallery = [];
        $http.get($scope.src).success(function(data){
           console.info("got data");
           $scope.gallery.length = 0;
           $scope.gallery = data;
        });
    }
}

在一般它的工作原理,我可以在Firebug控制台中看到:

In general it works and I can see in FireBug console:

enter directive controller
GET http://127.0.0.1/srv1
got data

但如果我把指令绑定的第二个实例到另一个网址:

But If I'm placing second instance of directive bind to another url:

<my-tag src="http://127.0.0.1/srv2">...

作品只有一个下列日志:

Works only one with following log:

enter directive controller
GET http://127.0.0.1/srv1
enter directive controller
GET http://127.0.0.1/srv2
got data             <-- as usual it relates to first directive

你能不能帮我什么是错2指令nstances

Couldn't you help me what is wrong with 2 directive nstances

推荐答案

首先我看不出有什么问题。您可以使用指令多次因此隔离范围为正道。

First of all I don't see any problem. You use directive several times therefore isolate scope is right way.

我只是改变了 SRC:@ SRC:=

演示<大骨节病> 小提琴

HTML

<div ng-controller = "fessCntrl"> 
    <my-tag src="'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'"></my-tag>

    <my-tag src="'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 3 Bukit Batok Street 1&sensor=true'"></my-tag>        
</div>

JS

app.directive('myTag', ['$http', function($http) {
return {
    restrict: 'E',
    transclude: true,
    replace: true,     
    scope:{
        src:"="       
    },
    controller:function($scope){
        console.info("enter directive controller");
        $scope.gallery = [];

    console.log($scope.src);

        $http({method: 'GET', url:$scope.src}).then(function (result) {
                           console.log(result);                              
                        }, function (result) {
                            alert("Error: No data returned");
                        });
    }
}
}]);

这篇关于角指令处理HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆