angular directive handles http request

Dewfy picture Dewfy · Mar 3, 2014 · Viewed 25.7k times · Source

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

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

Directive itself:

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;
        });
    }
}

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

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

Answer

Maxim Shoustin picture Maxim Shoustin · Mar 3, 2014

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

I just changed src:"@" to src:"=".

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