Passing data to a custom directive in AngularJS

I have a page that displays a bunch of thumbnails of images that are retrieved using http. I use ng-repeat to traverse the array and create html.
It works great.

I also create a custom directive that I bind as an attribute to the img elements generated by ng-repeat.
This also works great.

However, when I try to transfer data to the scope of my custom directive, then it all falls apart. Data binding fails, ng-repeat does not replace the url of the images, so I get 404 as the url is invalid. This is pretty much as possible.

Any help is appreciated since I am completely new to Angular.

my html template:

<div class="portfolioContent">
<div class="row">
    <div class="col-lg-3 col-md-4 col-sm-4 col-xs-6 col-padding" ng-repeat="gImg in gPhotos">
        <div class="photoframe">
                <img src="{{gImg.thumbnailUrl}}" url="{{gImg.imageUrl}}" image-gallery>
        </div>
    </div>

and my custom directive:

myApp.directive('imageGallery',function(){

return {
    restrict: 'A',
    scope: {
      url: '='
    },
    controller: function($scope){
        console.log($scope.url);
    }
}

});

+4
source share
3 answers

Try to change

scope: {
  url: '='
},

to

scope: {
  url: '@'
},

See here for a very simple example. Check out the console. See here what is the difference between =and @.

+3
source

When you specify the scope: {url: '='}, you specify the binding of the two-way model. The attribute passed as "url" must be a model, not an interpolated string.

Try the following:

<img ng-src="gImg.thumbnailUrl" url="gImg.imageUrl" image-gallery>
+3
source

Why are you still trying to isolate the area?

Try the following:

        myApp.directive('imageGallery',function(){
        return {
            restrict: 'A',
            link : function(scope,element.attributes){
                   console.log(attributes.url);
                  // will log your URL as an atribute
                  // here you can bind an even to do your job , Eg : click , mouseover
             }
        }
        });
+1
source

Source: https://habr.com/ru/post/1545611/


All Articles