angularjs - 如何在 View 加载后获得触发指令?

标签 angularjs angularjs-directive photoswipe

我知道这个问题已经被问过一千次了,但我想我已经尝试了我读过的所有解决方案,但似乎无法让它发挥作用。

我有一个 API,可以从中获取图像,将图像拉入 View 后,我希望它们使用 photoswipe 在移动设备上显示。

我有一个指令:

'use strict';

App.directive('photoswipe', function () {
return {
    replace: false,
    restrict: 'A',
    link: function photoSwipeLink(scope, element, attr) {
      scope.$watch(attr.photoswipe, function(value){
        angular.element('#gallery a').photoSwipe({
          enableMouseWheel: false,
          enableKeyboard: false
        });
      });
    }
  };
});

我在控制台中收到此错误:

Code.PhotoSwipe.createInstance: No images to passed.

我猜这是因为指令在 View 渲染之前运行。

如果我添加 $timeout 而不是 watch 那么代码就可以工作。不幸的是,这个解决方案并不好,因为从 API 获取数据可能会出现延迟。此外,该代码在超时内不起作用。

我已经尝试过,上面的代码,我尝试过使用 $viewcontentloaded,尝试过在 ng-repeat 中的最后一个元素之后触发函数,但都不起作用。

任何帮助将不胜感激。

编辑:

这是 HTML。

<h1>{{ gallery.headline }}</h1>
<ul id="gallery" photoswipe>
  <li class="gallery" ng-repeat="image in gallery.images">
    <a href="{{ image.url }}" alt="image.caption">
      <img ng-src="{{ image.thumb_url }}" class="thumb" alt="{{ image.caption }}" style="display: block;">
      <h3 class="headline">{{ image.caption }}</h3>
    </a>
  </li>
</ul>

最佳答案

我认为发生这种情况是因为 Angular 在将结果绑定(bind)到列表之前正在处理您的指令。这可能是一种竞争条件。解决这个问题的一种方法是这样做

$scope.$broadcast("picsDownloaded" ... 

获得结果后 Controller 中的事件。 在指令上,而不是

scope.$watch(attr.photoswipe ....

这样做

scope.$on("picsDownloaded" ....

并在该处理程序中应用 Jquery 插件。

关于angularjs - 如何在 View 加载后获得触发指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16528482/

相关文章:

javascript - 使用 Angular 通过 POST 操作提交表单

javascript - Angular array.push() 为 ng-repeat 创建一个副本

javascript - photoswipe 从 flickr 或其他 feed 获取图像?

angularjs - 如何在 TypeScript 中实现 ng.IDirectiveFactory

javascript - AngularJS 模型绑定(bind)并将模型值传递给 Controller ​​方法

angularjs - 将 angularjs 指令转换为 angular 10

AngularJS 提前输入 + 多选标签

javascript - 如何访问从父指令传递但在 Controller 中定义的子指令中的函数?

javascript - 是否可以从外部禁用共享按钮?

android - 如果用户向下/向上滑动,不要关闭 Photoswipe