gpt4 book ai didi

javascript - imagesLoaded 插件无法与 Angular JS 一起使用

转载 作者:行者123 更新时间:2023-12-02 16:48:49 24 4
gpt4 key购买 nike

所以我正在学习 AngularJS,并且正在构建一个小型网络应用程序,该应用程序允许您随机单击图像。基本上,您单击“下一个”按钮,就会下载并显示图像,当您单击“后退”按钮时,它会转到堆栈中的上一个图像。

我想显示一个加载微调器并禁用后退/前进按钮,直到新图像的 ajax 请求完成并且图像完全加载

我的图像 Controller 的结构如下:

app.controller('ImageController', ['imageService', function(imageService) {
var that = this;
that.position = 0;
that.images = [];
that.loading = false;

that.isLoading = function() {
return that.loading;
}

that.setLoading = function(isLoading) {
that.loading = isLoading;
}

that.currentImage = function() {
if (that.images.length > 0) {
return that.images[that.position];
} else {
return {};
}
};

that.fetchSkin = function() {
that.setLoading(true);
imageService.fetchRandomSkin().success(function(data) {
// data is just a js object that contains, among other things, the URL for the image I want to display.
that.images.push(data);

that.imagesLoaded = imagesLoaded('.skin-preview-wrapper', function() {
console.log('images loaded');
that.setLoading(false);
});
});
};

that.nextImage = function() {
that.position++;
if (that.position === that.images.length) {
that.fetchSkin();
}
};

that.previousImage = function() {
if (that.position > 0) {
that.position--;
}
};

that.fetchSkin();
}]);

如果您注意到 that.fetchSkin() 函数内部,我会调用 imagesLoaded 插件,然后在加载图像时将 that.loading 设置为 false。在我的模板中,当加载变量设置为 false 时,我使用 ng-show 显示图像。

如果我在imagesLoaded回调之外将loading设置为false(比如ajax请求完成时),那么一切都会按预期工作,当我在imagesLoaded函数内部设置它时,模板不会使用新的加载值进行更新。请注意 console.log('图片已加载');图像加载后会打印到控制台,因此我知道 imagesLoaded 插件工作正常。

最佳答案

作为您的imagesLoaded加载图像后会异步调用回调,Angular 不知道 that.isLoading() 的值方法调用发生了变化。正是由于脏检查,Angular 才为您提供了易于使用的 2 路数据绑定(bind)。

如果您有这样的模板: <div ng-show="isLoading()"></div>

更改值后它不会更新。

您需要手动告知 Angular 有关数据更改的信息,这可以通过手动调用 $digest 来完成。

$scope.$digest();

就在你这样做之后

 console.log('images loaded');
that.setLoading(false);

可以工作的伪代码(从我的指令复制并粘贴):

//inside your controller
$scope.isLoading = false;

// just another way of using imagesLoaded. Yours is ok.
$element.imagesLoaded(function() {
$scope.isLoading = true;
$scope.$digest();
});

只要您只在异步回调中更改 Controller $scope,就无需调用 $apply()在 $rootScope 上运行 $digest,因为您的模型更改只是本地的。

关于javascript - imagesLoaded 插件无法与 Angular JS 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26871501/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com