gpt4 book ai didi

javascript - 如何在 angularjs 中从 View 调用的另一个方法中使用 $http.then 响应?

转载 作者:行者123 更新时间:2023-11-30 11:36:07 25 4
gpt4 key购买 nike

我有一个 View ,它在表 td 中有一个函数来检查 td 是否有数据存储在数据库中。如果 td 有数据,它将显示为红色:

<tr ng-repeat="row in rows">
<td ng-repeat="column in columns" style="width: 100px; cursor: pointer"
ng-style="{background: getWeight(row, column) ? 'red' : '' }"
ng-click="onCellselect(row, column)">
@{{row}}@{{column}}
</td>
</tr>

JS:

  $http.get("api/getYardGraphDetails")

.then(function (r) {
console.log(r.data)

$scope.weights =r.data

})

$scope.getWeight = function (row, column) {
console.log($scope.weights)

// See if there's a record with the row and column.
var record = _.find($scope.weights, {
row: row,
column: column
});

// Was a record found with the row and column?
if (record) {
// If so return its weight.
return record.weight;
}

};

$scope.getWeight() 函数 $scope.weights 来自 $http.get 响应。但是 console.log($scope.weights)$scope.getWeight() 中返回 undefined

如何通过 $scope.getWeight() 从 $http.get 获取 $scope.weights ?

我认为我应该在 $http.get 从数据库返回数据后调用 $scope.getWeight()。由于 $http.get 是异步的,它不会等待响应,那是我的 $scope.weights$scope.getWeight() 中没有值(value)

最佳答案

假设 $http.get 在 Controller 初始化时被调用,一个简单的解决方案是用 ng-if 来保护它。像这样的东西:

<tr ng-if="weights" ng-repeat="row in rows">
<td ng-repeat="column in columns" style="width: 100px; cursor: pointer"
ng-style="{background: getWeight(row, column) ? 'red' : '' }"
ng-click="onCellselect(row, column)">
@{{row}}@{{column}}
</td>

这样,函数 getWeight() 将仅在填充 $scope.weights 后被调用。如果您需要多次调用 http,则应改为从 promise resolve 调用 getWeights()。

这行得通还是我遗漏了什么?

关于javascript - 如何在 angularjs 中从 View 调用的另一个方法中使用 $http.then 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44351375/

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