gpt4 book ai didi

asynchronous - Trigger.io + Angular.js 并在调用 forge.ajax 后更新 View

转载 作者:行者123 更新时间:2023-12-02 05:09:53 25 4
gpt4 key购买 nike

遇到问题,到目前为止,对于看似相似的 SO 问题无法找到任何解决方案。问题是这样的:

使用 Trigger.io 的 forge.ajax,我的 Angular.js View 在数据返回后没有更新。我意识到这是因为 forge.ajax 是一个异步函数,并且在 View 已经显示之后返回数据。我尝试使用 $rootScope.apply() 来更新 View ,但它对我不起作用,正如我看到的许多示例所示。

查看下面的 Controller 代码:

function OfferListCtrl($scope) {

$scope.offers = [];

$scope.fetchOffers = function(callback) {

$scope.offers = [];

var successCallback = function(odataResults) {
var rawJsonData = JSON.parse(odataResults);
var offers = rawJsonData.d;
callback(offers);
};

var errorCallback = function (error){
alert("Failure:" + error.message);
};

forge.request.ajax({
type: 'GET',
url: 'https://www.example.com/ApplicationData.svc/Offers',
accepts: 'application/json;odata=verbose',
username: 'username',
password: 'password',
success: successCallback,
error: errorCallback
});

};

$scope.fetchOffers(function(offers) {
$scope.offers = offers;
forge.logging.info($scope.offers);
});
}

那里的所有代码都可以正常工作,并且 $scope.offers 会填充数据库中的报价数据。日志记录功能显示数据正确,格式正确。

我曾尝试在合乎逻辑的地方(以及一些不合逻辑的地方)使用 $rootScope.apply(),但无法更新 View 。如果您对我如何使它起作用有任何想法,我将不胜感激。

编辑:添加 HTML

HTML 如下。注意带有 ng-click="refresh()"的按钮。这只是一种解决方法,因此我至少可以看到数据。它调用一个执行 $rootScope.apply() 的单行刷新函数,它会更新 View 。

   <div ng-controller="OfferListCtrl">
<h1>Offers</h1>
<ul>
<li ng-repeat="offer in offers">
<p>Description: {{offer.Description}}<br />
Id: {{offer.Id}}<br />
Created On: {{offer.CreatedOn}}<br />
Published: {{offer.Published}}<br />
</p>
</li>
</ul>
<input type="button" ng-click="refresh()" value="Refresh to show data" />
</div>

最佳答案

你需要改变

$scope.fetchOffers(function(offers) {
$scope.$apply(function(){
$scope.offers = offers;
});
forge.logging.info($scope.offers);
});

这是因为对 $scope 的所有更改都必须在 Angular 范围内进行,在这种情况下,因为您正在使用 forge 调用 ajax 请求,所以回调不是在 Angular 框架内执行,这就是它不起作用的原因。

您可以使用 $scope.$apply()在这种情况下,在 Angular 框架内执行代码。

查看$apply() 方法文档

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

关于asynchronous - Trigger.io + Angular.js 并在调用 forge.ajax 后更新 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15658485/

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