javascriptangularjsangularjs-directiveimgix

What is wrong with this AngularJS directive?


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?


Solution

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

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