gpt4 book ai didi

javascript - AngularJS 范围没有注意到变化

转载 作者:行者123 更新时间:2023-11-28 14:55:46 25 4
gpt4 key购买 nike

我有一个$scope我用于 ng-src 的字段<img>: 中的属性

$scope.imageDataUrl

该字段初始化如下:

$scope.myJsWrapper = new MyJsWrapper();
$scope.myJsWrapper.getImageUrl(function (imageDataUrl) {
$scope.imageDataUrl = imageDataUrl;
});

这里是外部 JS 函数:

function MyJsWrapper() {
this.getImageUrl = function (withImage) {
thirdPartyJsFile.getData().then(function (data) {
var imageDataUrl = thirdPartyJsFile.getDataUrl(data, "image/png");
if (withImage) {
withImage(imageDataUrl);
}
});
}
}

这是一种复杂的方法,但第三方应用程序强制我这样做。我遇到的问题是,以某种方式, Angular 没有注意到字段 imageDataUrl 的变化。所以图片没有更新。我什至尝试过$scope.$watch对于该字段,但它没有被触发。有趣的是,当我在浏览器中滚动或单击任意位置(以及 $scope.$watch )时,它会发生变化。

为什么 Angular 无法识别字段变化以及我需要做什么才能使其正常工作?

最佳答案

如果是第三方库正在更新您的$scope,为了让 Angular 上下文了解您的更改,您需要调用$scope.$apply()

$scope.$apply(function() {
$scope.imageDataUrl = imageDataUrl;
});

在你的回调中

参见docs

$apply() is used to execute an expression in AngularJS from outside of the AngularJS framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the AngularJS framework we need to perform proper scope life cycle of exception handling, executing watches.

关于javascript - AngularJS 范围没有注意到变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42963390/

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