4

I have a page that displays a bunch of thumbnails of images that are retrieved using http. I use ng-repeat to go through the array and generate the html.
This works fine.

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

However, when I try to pass 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 end up getting a 404 since the url is invalid. That is pretty much as far as it goes.

Any help is greatly 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);
    }
}

});

hitautodestruct
  • 20,081
  • 13
  • 69
  • 93
Quantum_Entanglement
  • 1,583
  • 7
  • 21
  • 32

3 Answers3

5

Try changing

scope: {
  url: '='
},

to

scope: {
  url: '@'
},

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

Community
  • 1
  • 1
Jorg
  • 7,219
  • 3
  • 44
  • 65
3

When you specify scope: { url:'=' }, you are specifying two-way model binding. The attribute passed as 'url' should be a model, not an interpolated string.

Try this:

<img ng-src="gImg.thumbnailUrl" url="gImg.imageUrl" image-gallery>
Michael Kang
  • 52,003
  • 16
  • 103
  • 135
  • Your answer was also useful in helping me understand the the two way binding relationship, however since I don't want/need to update the value of gImg.thumbnailUrl in my directive this won't work. After Angular compiles this I end up with: `` – Quantum_Entanglement Jun 23 '14 at 17:10
  • Since it is bound to a model, it should work. Likely, there is something else going on. But if attribute binding works, that's good to hear. – Michael Kang Jun 23 '14 at 17:21
1

Why are you trying to isolate scope anyway ?

Try this :

        myApp.directive('imageGallery',function(){
        return {
            restrict: 'A',
            link : function(scope, element, attributes){
                   console.log(attributes.url);
                  // will log your URL as an attribute
                  // here you can bind an even to do your job , E.g. : click , mouseover
             }
        }
        });
Mr. AK
  • 89
  • 11
Milad
  • 27,506
  • 11
  • 76
  • 85