用于ElevateZoom jQuery插件的AngularJS指令

Pet*_*ton 7 javascript jquery angularjs angularjs-directive

我正在尝试在角度应用程序中使用ElevateZoom jQuery插件.

基本上,要正常使用ElevateZoom,您可以按如下方式创建图像:

<img id="my-img" src="small.jpg" data-zoom-image="big.jpg" />
Run Code Online (Sandbox Code Playgroud)

然后在你的应用程序JS中:

$('#my-img').elevateZoom(options);
Run Code Online (Sandbox Code Playgroud)

这在标准应用程序中工作正常.但是当我尝试使用指令在我的AngularJS应用程序中执行它时(我遵循了一些SO的答案,将jquery插件转换为带指令的角度)我无法使其工作.

关于Plunkr的实时可编辑演示:http://plnkr.co/edit/Mu4EOcGtGs7XVDDUvnnB?p = preview

我的指令如下:

app.directive('ngElevateZoom', function() {
  return {
    restrict: 'A',
    scope: true,
    compile: function(scope, element, attrs) {
      $(element).elevateZoom(scope.$eval(attrs.elevateZoom));
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

我的HTML看起来像这样:

<img ng-elevate-zoom ng-src="{{small_image}}" data-zoom-image="{{large_image}}" />
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?我几天只试过Angular,所以对我很轻松;)

dim*_*irc 16

你的指令:

app.directive('ngElevateZoom', function() {
  return {
    restrict: 'A',
    scope: true,
    compile: function(scope, element, attrs) {
      $(element).elevateZoom(scope.$eval(attrs.elevateZoom));
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

请记住,compile函数(tElement,tAttrs,transclude){...}无法访问范围,所以我猜你试图使用该link函数.

点击这里

我做了一些改变:

HTML

<img ng-elevate-zoom
     ng-src="{{small_image}}"
     zoom-image="{{large_image}}" />
Run Code Online (Sandbox Code Playgroud)

JS

app.directive('ngElevateZoom', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      element.attr('data-zoom-image',attrs.zoomImage);
      $(element).elevateZoom();
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

当直接使用时data-zoom-image='{{large_image}}',导致elevateZoom尝试从该属性获取值,并且在运行插件时它是'{{large_image}}'$(element).elevateZoom();

在此输入图像描述

检查更新的Plunker


更新

由于可能存在attrs需要插件延迟的情况,你需要$观察 attr并且只有当它实际准备好你调用插件时.

app.directive('ngElevateZoom', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {

      // Watch for changes on the attribute before
      // calling the function.
      attrs.$observe('zoomImage', function() {
        linkElevateZoom();
      });

      function linkElevateZoom() {
        // Check that it's not empty.
        if (!attrs.zoomImage) return;
        element.attr('data-zoom-image',attrs.zoomImage);
        $(element).elevateZoom();
      }

      linkElevateZoom();
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

检查更新的plunker

可选 当与视图一起使用时,插件会在视图顶部留下div.这是解决该问题的指令.

app.directive('zoomContainer', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            scope.$on('$routeChangeSuccess', function() {
                var target = element.children('div.zoomContainer').remove();
            });
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

该指令需要应用于body元素.

<body zoom-container>
Run Code Online (Sandbox Code Playgroud)