渲染后的AngularJS和jQuery插件
我正在构建一个滑块,我正在使用ng-repeat指令迭代(RESTful)服务以在滑块中创建幻灯片。
我已经将滑块包装在自定义指令中,以便在完成后初始化它(即在链接函数中)。
var swiper = angular.module('ng-swiper', ['qbusService']) .directive('swiper', function(){ return { link : function(scope, element, attrs) { $(element).swiper({}); } }; });
但是滑块没有正确初始化,我错过了什么?
HTML:
您可以让swiper启动(或更新)事件:
var swiper = angular.module('ng-swiper', ['qbusService']) .directive('swiper', function(){ return { link : function(scope, element, attrs) { element.swiper({}); scope.$on("swiper-update", function(){ element.swiper({}); }) } }; });
并且每个幻灯片触发它(有效更新每个新幻灯片的滑块)或仅在ng-repeat完成时触发它(使用ng-repeat的$ scope中的$ last属性)。
或者,您不需要为此创建指令,只需使用ng-init来运行更新function,例如:
并在父作用域上有相应的function:
var swiper = angular.module('ng-swiper', ['qbusService']) .directive('swiper', function(){ return { link : function(scope, element, attrs) { scope.updateSwiper = function(bool){ if (bool) element.swiper({}); } } }; });
尝试用jQuery的ready事件包装它
var swiper = angular.module('ng-swiper', ['qbusService']) .directive('swiper', function(){ return { link : function(scope, element, attrs) { $(function() { $(element).swiper({}); }); } }; });
尝试用$timeout
包装,让浏览器有机会在完成角度编译过程后完成DOM的绘制:
var swiper = angular.module('ng-swiper', ['qbusService']) .directive('swiper', function($timeout){ return { link : function(scope, element, attrs) { $timeout(function(){ $(element).swiper({}); },10) } }; });