在AJAX API调用后如何更新Angular控制器

How can I update an Angular controller after an AJAX API call?

本文关键字:更新 Angular 控制器 何更新 API AJAX 调用      更新时间:2023-09-26

我正在创建一个天气预报应用程序,使用ng repeat迭代我的forecast.dayArray来在页面中创建不同的日期。

问题是,用于在每个"一天"中填充数据的控制器没有使用从ajax API调用解析的信息进行更新。相反,它只保留初始化时使用的值。

//Initialize
var app = angular.module("weather", []);
app.controller("ForecastController", function(){
    this.array = ['a','b','c'];
});
ajaxCall(){
success: function(){
     app.controller.array.push('d'); //Doesn't seem to work
};

您可以在这里看到完整的代码:My Codepen

在您的示例中,app.controller是一个用于设置新控制器的函数,因此在这一行中:

app.controller.array.push('d');

app.controller不是对您的"ForecastController"的引用。

解决这个问题的一个简单方法是在控制器内进行AJAX调用,$http服务:

app.controller("ForecastController", ["http", function ($http) {
    this.array = ['a', 'b', 'c'];
    $http
        .get(...)
        .then(function (response) {
            this.array.push('d');
        });
}]);

虽然这是可行的,但通常认为更好的做法是将数据提取分离到自己的服务中,并将新服务注入控制器。

您将不得不使用$http服务。您可以在控制器级别注入它,也可以用工厂/服务抽象它。

var app = angular.module("weather", []);
app.controller("ForecastController", ['$http', function($http) {
  this.array = ['a', 'b', 'c'];
  $http.get('someURLhere').then(function(response) {
    //http call success!
    this.array.push('d');
  }, function(error) {
    //error here! handle the error
    alert(error.data)
  })
}]);

您可以在此处阅读有关如何使用$http服务的信息。

不需要使用$http服务,您仍然可以使用$scope从角度外更新作用域$应用