我正在尝试在我的指令创建的渲染元素上启动轮播脚本。如果我为指令提供静态 json,它会工作,但如果我使用 http get 从 api 获取数据,它将无法正确初始化。虽然脚本确实初始化并创建了一组用于轮播导航的元素,但似乎在发生这种情况后注入(inject)了呈现的元素。
如果我将 init 延迟 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']);
最佳答案
你应该使用 promise 。 promise 会在显示数据之前等待数据,但它仍会运行 Controller 中的其他函数,类似于 c# 中的异步函数。这是教程的链接 https://docs.angularjs.org/api/ng/service/ $q
关于javascript - Angularjs – 在 ng-repeat 不适用于 http get 后初始化脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29904299/