1

I am trying to write a imgix directive for AngularJS. Here is my code:

MetronicApp
.directive('imgix', function() {
    return {
        replace: true,
        scope: {
            url: '='
        },
        restrict: "A",
        template: "<img class='thumbnail inline' width={{w}} height={{h}} src='https://mysite.imgix.net/{{url}}?h={{h}}&w={{w}}&fit=crop'>",
        link: function(scope, elm, attrs) {
            function ctrl(value, mode) {
                // check inputs
                if ((value === null) || (value === undefined) || (value === '')) {
                    // let's do nothing if the value comes in empty, null or undefined
                    return;
                }

                scope.h = attrs.height || 50;
                scope.w = attrs.width || 50;
                scope.url = value;


            }

            // by default the values will come in as undefined so we need to setup a
            // watch to notify us when the value changes
            scope.$watch(attrs.url, function(value) {
                ctrl(value, 'url');
            });
        }
    };
});

And in html, I have 2 images:

 <img imgix data-height="200" data-width="200" url="theme.options.homepageBackground" />

 <img imgix data-height="200" data-width="200" url="theme.options.menuBackground" />

But the result is like in the picture:

enter image description here

I didn't understand what is wrong. Is there something about scope?

Fred
  • 4,195
  • 2
  • 29
  • 42
Burak
  • 5,706
  • 20
  • 70
  • 110

3 Answers3

1

I suggest using ng-src attribute and passing the whole url from your link function to the directive.

1

Your directive scope is bound to the parent scope. Either use a child or isolated scope instead.

MetronicApp.directive('imgix', function() { return { scope: { url: '=' }

0

I solved the issue with the combination of Matthias and Julien

First, I added curly brackets to the directive:

<imgix data-height="200" data-width="200" url="{{theme.options.menuBackground}}" />

Then I added scope: {} to the directive code

And I saw that value in watch code returns undefined. I changed with that:

scope.$watch(attrs.url, function(value) {
                ctrl(attrs.url, 'url');
            });

Now it works. Thank you.

Burak
  • 5,706
  • 20
  • 70
  • 110