angular指令处理http请求

时间:2014-03-03 08:35:45

标签: angularjs http directive

我有一个接受url来获取远程数据的angular指令:

<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控制台中看到:

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

但是如果我将指令的第二个实例绑定到另一个url:

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

只能使用以下日志:

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指令的问题

1 个答案:

答案 0 :(得分:21)

首先,我没有看到任何问题。你多次使用指令因此隔离范围正确。

我刚刚将src:"@"更改为src:"="

演示 Fiddle

<强> 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");
                        });
    }
}
}]);