Image loading issue in custom directive

653 views Asked by At

I want the image URL received from server side in my custom directive. The directive is used to create a canvas.

Seems the directive is loaded and the image URL is undefined. As it takes the time to get the URL from the server side.

Or maybe how did I get $rootScope data in my directive link function.

Edit:

The following is the directive:

app.directive('logocanvasdirective',['$rootScope','$templateRequest','$compile', function($rootScope,$templateRequest,$compile) {
return {
    template: "<canvas id='logo' width='500' height='500'/>",
    scope: true,
    link: function($scope, element, attrs) {
        var canvas1 = document.getElementById('logo'),
        context1 = canvas1.getContext('2d');

        make_base1();

        function make_base1()
        {
          base_image1 = new Image();
          base_image1.src =scope.variable; //How do I use this?
          base_image1.onload = function() {
            context1.drawImage(base_image1, 0, 0);
          }
        }
    }
};
}]);

I want the image.src = $scope.variable which is receive from server side in my controller.

How do I do that ?

1

There are 1 answers

1
Shashank Agrawal On BEST ANSWER

You need to use $watch since you are getting the src from an asynchronous AJAX call:

app.directive('logocanvasdirective',['$rootScope','$templateRequest','$compile', function($rootScope,$templateRequest,$compile) {
return {
    template: "<canvas id='logo' width='500' height='500'/>",
    scope: {
         imgSrc: '='
    },
    link: function($scope, element, attrs) {
        var canvas1 = document.getElementById('logo'),
        context1 = canvas1.getContext('2d');

        make_base1();

        function make_base1()
        {
          base_image1 = new Image();
          base_image1.src = scope.imgSrc;
          base_image1.onload = function() {
            context1.drawImage(base_image1, 0, 0);
          }
        }

        scope.$watch('imgSrc', function(newValue) {
             if (newValue) {
                 make_base1();
             }
        });
    }
};
}]);

And pass the $scope.variable to your directive:

 <logocanvasdirective img-src="variable" />

Or

<div logocanvasdirective img-src="variable"></div>