自定义指令中的图像加载问题

时间:2016-02-11 08:40:36

标签: angularjs canvas angularjs-directive angularjs-rootscope

我想在我的自定义指令中从服务器端收到图像URL。 该指令用于创建画布。

似乎已加载该指令且图像URL未定义。因为从服务器端获取URL需要时间。

或者我如何在我的指令链接功能中获取$rootScope数据。

编辑:

以下是指令:

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

我想要在我的控制器中从服务器端接收的image.src = $scope.variable

我该怎么做?

1 个答案:

答案 0 :(得分:2)

您需要使用$watch,因为您从异步AJAX调用中获取src

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>