使用AngularJS的外部库(灯箱)

Seb*_*eit 1 javascript angularjs angularjs-directive

我正在使用AngularJS,我想添加一个用于显示图像的灯箱.我的灯箱代码就像这样(我使用的是shadowbox):

<a href="myimage.jpg" rel="shadowbox">image name</a>
Run Code Online (Sandbox Code Playgroud)

但是当我想像AngularJS一样使用shadowbox时:

<a ng-repeat="pic in pics" href="{{pic}}" rel="shadowbox">image name</a>
Run Code Online (Sandbox Code Playgroud)

阴影框将被忽略,它的工作方式类似于普通链接.使这项工作的最佳方法是什么?

我可能要写一个指令,但我不熟悉它...

Pas*_*ert 5

我认为shadowbox只处理DOM一次,并且不会注册AngularJS的DOM修改.

通常的方法是编写一个实例化Shadowbox的包装器指令.我建议你直接调用Shadowbox,而不是使用带rel="shadowbox"属性的自动设置.基本上有两个步骤:

  1. 为Shadowbox 设置指令
  2. 在指令的作用域中注册一个函数,在单击链接时将调用该函数.阅读有关如何执行此操作的Shadowbox文档API文档.

指令原型:

angular.module('yourModuleName') // you can use your own name here
.directive('shadowbox', function() {
  return {
    // here you can style the link/thumbnail/etc.
    template: '<a ng-click="openShadowbox()">{{imageName}}</a>',
    scope: {
      imageName: '@name',
      imageUrl: '@url'
    },
    link: function (scope, element, attrs) {

      // the function that is called from the template:
      scope.openShadowbox = function () {

        // see Shadowbox documentation on what to write here.
        // Example from the documentation:

        Shadowbox.open({
          content:    '<div id="welcome-msg">Welcome to my website!</div>',
          player:     "html",
          title:      "Welcome",
          height:     350,
          width:      350
        });
      };

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

用法:

<a shadowbox name="image name" url="image url"></a>
Run Code Online (Sandbox Code Playgroud)