我最近遇到了同样的问题。在reddit上找到了这个答案:
http://as.reddit.com/r/angularjs/comments/1ksa5k/help_getting_swiper_to_work_in_a_directive_with/
他的解决方案:
http://plnkr.co/edit/JUkBe6tULkWL2Jx343tx?p=preview
用户deathcarrot在那里写道:
看起来 swiper 在加载时会破坏您的 DOM,这会破坏绑定。在您添加任何内容之前,在您的 swiperDirective 链接函数中运行 swiper({...}),然后在准备好激活它后在 doReady 中运行 mySwiper.reInit()。可能还需要 $watchCollection 你的 ng-repeat 数据和 reInit() 每当它发生变化时更新幻灯片。
这是我在项目中使用它的方式:
在 html 文件中,我添加了两个自定义指令(swiper-directive 和 swiper-slide 到整个 swiper-div-thing
<div class="swiper-container" swiper-directive>
<div class="swiper-wrapper">
<div class="swiper-slide" ng-repeat="item in data" swiper-slide>
{{$index}} : {{item}}
</div>
</div>
</div>
在我的 angular.run 函数中,我向 rootscope 添加了一个函数 updateSwiper():
var mySwiper;
var myApp= angular.module('testApp',[])
.run( function($log, $rootScope, $http, $templateCache){
$rootScope.updateSwiper = function () {
mySwiper.reInit();
}
}
我这样定义的指令:
myApp.directive("swiperDirective", ["$rootScope", function($rootScope) {
return {
restrict: "A",
controller: function() {
this.ready = function() {
$rootScope.updateSwiper();
}
},
link: function(scope, element, attrs, ctrl) {
mySwiper = new Swiper(".swiper-container", {
loop:false
});
}
}
}]);
myApp.directive("swiperSlide", [function() {
return {
restrict: "A",
require: "^swiperDirective",
link: function(scope, element, attrs, ctrl) {
if(scope.$last) {
ctrl.ready();
}
}
}
}]);
所以基本上每个创建的幻灯片都会调用 swiperSlide 指令中的 link: function。 ng-repeat 中的每个元素都有自己的作用域,只有我们数据数组中的最后一项定义了 $last,所以它显然命中了函数ctrl.ready()。然后这会调用函数$rootScope.updateSwiper,最终我们的 swiper 会重新初始化。
有了这个,swiper 可以很好地与 angular 配合使用,也可以在移动设备 (phonegap) 上使用。所以我希望这就是你要找的...