Problem loading image in user directive

I want the image URL to be retrieved from the server in my custom directive. The directive is used to create the canvas.

The directive seems to be loaded and the image url is undefined. Since it takes time to get the URL from the server side.

Or maybe how I got the data $rootScopein my 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 that image.src = $scope.variablewhich is accepted by the server side in my controller.

How to do it?

+4
source share
1 answer

$watch, src AJAX:

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();
             }
        });
    }
};
}]);

$scope.variable :

 <logocanvasdirective img-src="variable" />

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

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


All Articles