【发布时间】:2015-04-27 19:26:59
【问题描述】:
我正在尝试在我的指令创建的渲染元素上启动轮播脚本。如果我用静态 json 提供指令,它会起作用,但如果我使用 http get 从 api 获取数据,它将无法正确初始化。虽然脚本确实初始化并创建了一组用于轮播导航的元素,但似乎渲染的元素在发生这种情况后被注入。
如果我将初始化延迟 100 毫秒,它将正确初始化,但感觉就像一个 hacky 解决方案。在这种情况下,最佳做法是什么?
静态数据 - 有效
angular.module('exhibitions', [])
.directive('exhibitionsCarousel', ['$timeout', function(timer) {
return {
scope: {},
link: function(scope, element, attrs) {
var initFlickity = function () {
var flkty = new Flickity( '.main-gallery', {
cellAlign: 'left',
contain: true
});
};
timer(initFlickity, 0);
},
templateUrl: '/app/themes/pomgallery/exhibitions_carousel.html',
replace: true,
controller: 'exhibitionsCarouselCtrl',
controllerAs: 'ctrl'
};
}])
.controller('exhibitionsCarouselCtrl', function($scope, $http) {
this.exhibitions = [
{title: 'Rachel', date: 'Washington', place: 'One'},
{title: 'Joshua', date: 'Foster', place: 'Two'},
{title: 'Samuel', date: 'Walker', place: 'Three'}
];
});
angular.module('PomGallery', ['exhibitions']);
获取的数据 - 无法立即工作
angular.module('exhibitions', [])
.directive('exhibitionsCarousel', ['$timeout', function(timer) {
return {
scope: {},
link: function(scope, element, attrs) {
var initFlickity = function () {
var flkty = new Flickity( '.main-gallery', {
cellAlign: 'left',
contain: true
});
};
timer(initFlickity, 0); // If I set it to 100 rather than 0 it'll work.
},
templateUrl: '/app/themes/pomgallery/exhibitions_carousel.html',
replace: true,
controller: 'exhibitionsCarouselCtrl',
controllerAs: 'ctrl'
};
}])
.controller('exhibitionsCarouselCtrl', function($scope, $http) {
var vm = this;
$http({
method: 'GET',
url: '/wp-json/posts',
params: {
'filter[posts_per_page]': 3
},
}).
success( function( data, status, headers, config ) {
vm.exhibitions = data;
}).
error(function(data, status, headers, config) {});
});
angular.module('PomGallery', ['exhibitions']);
【问题讨论】:
标签: javascript angularjs timer get