加载图像时动态添加AngularJS中的ng-click

时间:2017-04-09 15:17:20

标签: javascript html angularjs

我想在加载图像源时动态地将ng-click添加到元素。我现在就这样做:

$scope.compile = function(element) {
  var el = angular.element(element);
  $scope = el.scope();
  $injector = el.injector();
  $injector.invoke(function($compile) {
    $compile(el)($scope)
  })
};

$scope.showImagePreview = function(url) {

  fabric.util.loadImage(url, function(image) {

    if (image) {
      $scope.$apply(function() {

        var myEl = angular.element(image);
        myEl.attr('ng-click', 'openImage()');
        $scope.compile(myEl);

        $('.img-preview').append(myEl);
        $scope.canOpenImage = true;
      });
    }
  });
};

但是我一直收到错误 - 无法调用未定义的调用。我做错了什么?

1 个答案:

答案 0 :(得分:0)

嗯m8,你没有提供你的孔码,所以我不能给你一个完整的合格答案。 IMO你应该保持简单。您不需要fabric.js$compile$scope.$apply$injectorangular.element()来创建这样简单的处理。您可以使用本机JavaScript和AngularJS的强大功能轻松完成。以这种方式看看这个简单的方法。

视图

<div ng-controller="MyCtrl">
   <a ng-click="openImage()">
     <img ng-src="{{src}}" ng-click="" loaded-state="imageLoaded" imageonload />
   </a>
</div>

AngularJS应用程序

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($scope) {
    $scope.src = 'https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150';
    $scope.imageLoaded = false;
    $scope.openImage = function () {
      if ($scope.imageLoaded) {
        //function allowed to execute when image was loaded
        console.log($scope.imageLoaded);
      }
    }
});

myApp.directive('imageonload', function() {
    return {
        restrict: 'A',
        scope: {
          loadedState: "="
        },
        link: function(scope, element, attrs) {
            element.bind('load', function() {
               scope.loadedState = true;
            });
        }
    };
});

&GT;&GT; Demo fiddle