在Angular JS中初始化jQuery插件(RoyalSlider)
试图加载RoyalSlider作为指令。 这是我的指令,虽然我不确定为什么,在第一次加载但不在后续加载时有效:
app.directive('royalSlider', ['$timeout', function($timeout) { $(".royalSlider").royalSlider({ keyboardNavEnabled: true, arrowsNav: true, arrowsNavHideOnTouch: true, imageScaleMode: 'fill', slidesSpacing: 0 }); }]);
有错误:
TypeError: Cannot read property 'compile' of undefined
假设在所有内容完成时加载问题,我将其更改为:
app.directive('royalSlider', ['$timeout', function($timeout) { return { link: function ($scope, element, attrs) { $scope.$on('$viewContentLoaded', function () { $(".royalSlider").royalSlider({ keyboardNavEnabled: true, arrowsNav: true, arrowsNavHideOnTouch: true, imageScaleMode: 'fill', slidesSpacing: 0 }); }) } } }]);
没有任何事情发生。 $ timeout也在那里,因为我也尝试过这个技巧,但无济于事。
试试这个
app.directive('royalSlider', ['$timeout', function($timeout) { return { link: function ($scope, element, attrs) { $scope.$apply($(".royalSlider").royalSlider({ keyboardNavEnabled: true, arrowsNav: true, arrowsNavHideOnTouch: true, imageScaleMode: 'fill', slidesSpacing: 0 })); } } }]);
要么
app.directive('royalSlider', ['$timeout', function($timeout) { return { link: function ($scope, element, attrs) { $(".royalSlider").royalSlider({ keyboardNavEnabled: true, arrowsNav: true, arrowsNavHideOnTouch: true, imageScaleMode: 'fill', slidesSpacing: 0 }); $scope.$apply(); } } }]);
我已经有两种情况,其中指令和服务/工厂不能很好地发挥作用。
场景是我有一个指令,它有一个服务的dependency injection,并从指令我要求服务进行ajax调用(使用$ http)。
最后,在两种情况下,即使我给arrays一个初始值,ng-repeat根本也没有归档。
我甚至尝试用控制器和隔离范围制定指令。 只有当我把所有东西都移到控制器上时,它就像魔法一样。 其中一个是皇家滑块。
这是我的代码
app.service('AjaxService', ['$log', '$http', function ($log, $http) { var me = this; me.CallHttpAjaxAndMapSearch = function (url, targetObjext, propertyName, callback, splitObject) { $http.get(url) .success(function(data){ //etc., mapping to selectedArray if (propertyName) { targetObjext[propertyName] = selectedArray; } else { targetObjext['selectedArray'] = selectedArray; } if (callback) { callback(); } }); }; }]); app.service('slidersService', ['$log', '$http', 'AjaxService', function ($log, $http, AjaxService) { var me = this; me.initRoyalSlider = function (url, element, arrayName, sliderOptions, splitObject) { me[arrayName] = []; var successCallback = function slidersService_successCallback() { setTimeout(function slidersService_successCallback_Timeout() { $log.log('setTimeout for ' + arrayName); element.royalSlider(sliderOptions); }, 0); }; AjaxService.CallHttpAjaxAndMapSearch(url, me, arrayName, successCallback, splitObject); }; }]); app.controller('royalSlider', function ($scope, $attrs, $log, slidersService) { var arrName = $attrs.royalSlider; var options = JSON.parse($attrs.royalSliderOptions); var element = $attrs.$$element; $scope.svc = slidersService; slidersService.initRoyalSlider($attrs.royalSliderUrl, element, arrName, options, $attrs.splitObject); });
和HTML