问题描述
我知道这已经被问了一千次了,但我想我已经尝试了我读过的所有解决方案,但似乎无法让它发挥作用.
I know this has been asked a thousand time, but I think I've tried every solution I've read and I can't seem to get it to work.
我有一个 API,我可以从中获取我的图像,在将图像拉入视图后,我希望它们使用 photowipe 在移动设备上显示.
I have an API from which I'm getting my images, after pulling the images into the view I want them to use photoswipe for displaying on mobile.
我有一个指令:
'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
});
});
}
};
});
我在控制台中收到此错误:
I get this error in the console:
Code.PhotoSwipe.createInstance: No images to passed.
我猜这是因为指令在视图呈现之前正在运行.
I guess this is because the directive is running before the view has rendered.
如果我添加 $timeout 而不是 watch,那么代码就可以工作.不幸的是,这个解决方案并不好,因为从 API 获取数据可能会有延迟.此外,代码在超时内不起作用.
If I add a $timeout instead of watch then the code does work. Unfortunately this solution is no good, as there could be a delay in getting the data from API. Also, the code doesn't work within the timeout.
我试过,上面的代码,我试过使用 $viewcontentloaded,试过在 ng-repeat 中的最后一个元素之后触发函数,但都不起作用.
I have tried, the above code, I've tried using $viewcontentloaded, have tried firing function after last element in ng-repeat, but neither work.
任何帮助将不胜感激.
这是 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 在结果绑定到列表之前处理您的指令.这可能是一个竞争条件.解决这个问题的一种方法是做
I think this is happening because Angular is processing your directive before the results are bound to the list. It is probably a race condition. One way to solve this is to do
$scope.$broadcast("picsDownloaded" ...
获得结果后在控制器中的事件.在指令上,而不是
event in your controller after you get the results.On the directive, instead of
scope.$watch(attr.photoswipe ....
这样做
scope.$on("picsDownloaded" ....
并在该处理程序中应用 Jquery 插件.
and in that handler you apply the Jquery Plugin.
这篇关于如何在视图加载后获得指令触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!