Angularjs 如何将脚本设置为在加载所有照片后运行?
我已经花了几个小时尝试了网上提供的所有不同的方法,但没有任何效果。我只想加载一个脚本,在加载所有图像后运行。是不是有什么东西不允许我这么做?我正在使用Angularjs 如何将脚本设置为在加载所有照片后运行?,angularjs,Angularjs,我已经花了几个小时尝试了网上提供的所有不同的方法,但没有任何效果。我只想加载一个脚本,在加载所有图像后运行。是不是有什么东西不允许我这么做?我正在使用$routeProvider: var photos = { name: 'photos', url: '/photos', views: { main: { templateUrl: "views/photos/photos.html", controller
$routeProvider
:
var photos = {
name: 'photos',
url: '/photos',
views: {
main: {
templateUrl: "views/photos/photos.html",
controller: function($scope,$http){
$http({
url: 'get/photos',
method: "POST"
})
.success(function (data, status, headers, config) {
$scope.data = data;
// this doesn't work
$(window).load(function() {
myScript();
});
})
.error(function (data, status, headers, config) { $scope.status = status; });
}
}
}
};
顺便说一下,我在控制台中没有收到任何错误。在我看来,http POST调用检索照片。我假设
myScript
是一个函数。那么为什么不试试这个呢:
var photos = {
name: 'photos',
url: '/photos',
views: {
main: {
templateUrl: "views/photos/photos.html",
controller: function($scope,$http){
$http({
url: 'get/photos',
method: "POST"
})
.success(function (data, status, headers, config) {
$scope.data = data;
myScript();
})
.error(function (data, status, headers, config) {
$scope.status = status;
});
}
}
}
};
因为
myScript
函数仅在POST
成功后运行。我假设数据
指的是实际的图像数据。我不知道我是否真的理解您试图获取的数据类型,但我认为您可以尝试承诺
Angular中的$http已返回一个封装在.success或.error中的承诺,但您也可以像其他承诺一样使用.then()回调
因此,如果问题是等待success()回调完成,您可以这样做,用几个then()替换它:
我做了一点解释:
它使用$timeout模拟较长的响应时间,因此您必须等待3秒钟才能看到修改后的数据,这些数据在调用myScript()函数之前保持初始状态。AFAIK,Angular没有提供在图像加载完成时通知我们的方法。 您需要为此编写自己的指令。该指令将封装必要的JavaScript/jQuery代码,用于检测一个或多个图像的已完成加载条件
也许会有帮助。我不知道angularjs,但当我读到这个问题的标题时,我对你的方法很好奇。如果你能得到要加载的照片数量,你可以简单地使用一个计数器,然后在达到计数器时启动脚本?这是我最初尝试的,但它不起作用。由于某些原因,
myScript()
函数在加载所有照片之前运行。我意识到它应该在它们进入DOM后运行,但是函数需要在图像实际加载后运行。
$http.post(...).then(
//function which will wait for the data to be downloaded
//here you can alter data, check some values etc...
).then(
//the script for what you want after
myScript();
);