4

我希望在我的自定义指令中从服务器端接收到图像 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从我的控制器中的服务器端接收的。

我怎么做 ?

4

1 回答 1

2

您需要使用$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>
于 2016-02-11T09:00:50.650 回答