gpt4 book ai didi

angularjs - 如何将 promise 分配给范围

转载 作者:行者123 更新时间:2023-12-03 06:32:03 24 4
gpt4 key购买 nike

如何将 $promise 分配给 $scope.advertiserName?在下面的示例中,Console.log($scope.title) 返回“undefined”。

 Restangular.all('advertiser').one("?id=" + 1).getList().then(function(data) {
$scope.advertiserName = data.name;
$scope.advertiserId = data.id;
});

$scope.title = $scope.advertiserName;
$scope.id = $scope.advertiserId;

最佳答案

我们可以使用回调函数在获得ajax调用的响应后执行代码行。您可以访问此博客以获取有关回调函数的精彩解释http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/ 。让我们通过代码来理解它。

    $scope.setNameId = function (title,id,callBackFunction) {
Restangular.all('advertiser').one("?id=" + 1).getList().then(function(data) {
// $scope.advertiserName = data.name;
$scope.title= data.name;
// $scope.advertiserId = data.id;
$scope.id=data.id;
callBackFunction();
});
}
$scope.setNameId($scope.title,$scope.id,executeAfterResponse);
var executeAfterResponse=function(){
//code that you want to execute when value of $scope.title and $scope.id has changed
};

我们也可以通过这种方式来实现

$scope.setNameId(executeAfterResponse);

没有将 $scope.title$scope.id 变量作为 $scope 在 $scope.setNameId 函数的参数中传递 变量可以在同一文件内直接访问。

不需要注释的代码行,因为我们直接为 $scope.name$scope.id 赋值。

关于angularjs - 如何将 promise 分配给范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31207077/

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