在调用AJAX之后显示ng控制器的内容;作为“;作用

Displaying the contents of ng-controller after calling AJAX with the "as" function

本文关键字:作为 作用 控制器 AJAX 调用 之后 显示 ng      更新时间:2023-09-26

调用AJAX(即$http)后,我试图显示ng-repeat的内容

    <table ng-controller="TableController as tc">
        <tr>
            <th>Date</th>
            <!-- other headers are here -->
        </tr>
        <tr ng-repeat="order in tc.orders" >
            <td ng-bind="order.id"></td> //It doesn't appear
            <td>@{{ order.id }}</td>     //It doesn't appear as well. I use Laravel, so I need to put @
        </tr>
    </table>

以下是的相关脚本部分

angular.module('adminAngular', ['ui.bootstrap','dialogs.main'])
.controller('TableController', function(dialogs, $http){
    var instance = this;
    this.orders = [];
    $http({
        method : "POST",
        url : "/admin/getOrders"
    }).then(function (response) {
        this.orders = response.data;
        console.log("Inside; "+this.orders.length);
        });
});

console.log("Inside; "+this.orders.length)中,我可以看到预期的数据被分配给了this.orders数组。然而,正如这篇文章的标题所暗示的,数组并没有显示ng-repeat="order in tc.orders"

我关注这个问题,但关注这个问题并不能解决这个问题。现在我怀疑原因在于as声明,我必须在这个场合使用它。

由于我在网上看不到太多关于as的信息资源,如果你能给我任何建议,我将不胜感激。

您应该在promise解析函数中使用instance分配给正确的实例(控制器实例):

angular.module('adminAngular', ['ui.bootstrap','dialogs.main'])
.controller('TableController', function(dialogs, $http){
var instance = this;
instance.orders = [];
$http({
    method : "POST",
    url : "/admin/getOrders"
}).then(function (response) {
    instance.orders = response.data;
    console.log("Inside; "+ instance.orders.length);
        });
});

通常将此实例命名为:vm指的是视图模型

示例:

angular.module('adminAngular', ['ui.bootstrap','dialogs.main'])
.controller('TableController', function(dialogs, $http){
var vm= this;
vm.orders = [];
$http({
    method : "POST",
    url : "/admin/getOrders"
}).then(function (response) {
    vm.orders = response.data;
    console.log("Inside; "+vm.orders.length);
    });
});