REST API调用后模型未更新

时间:2015-11-21 12:07:57

标签: angularjs asynchronous

我是AngularJS的新手并且一直在玩它以掌握它。我已经开始在控制器中处理$scope以及它如何用作视图和模型之间的上下文。我也开始处理Promises和异步网络电话。

但是,我已经重新设计了一个非常简单的项目,在控制器中使用this代替$scope,而不是传入$scope对象。

但是,在我进行异步调用以获取JSON文件以加载变量usdToForeignRates的情况下,视图似乎永远不会更新。所有其他属性都有效。我有什么想法我做错了吗?

注意:我可以让视图更新,如果我将this.usdToForeignRates更改为$scope.usdToForeignRate,则将范围传递给控制器​​,然后只需将index.html更改为引用{{ 1}}而不是usdToForeignRates

controllers.js: -

invoice.usdToForeignRates

index.html的: -

var financeApp = angular.module('financeApp', []);
financeApp.controller('invoiceController', ['$http', function($http) {
this.qty = 1;
this.cost = 2;
this.inCurr = 'EUR';
this.currencies = ['USD', 'EUR', 'CNY'];
this.usdToForeignRates = [];
this.counter = 1;

loadRates();
function loadRates(){
    $http.get('rates/rates.json').then(function(rates)
    {
        this.usdToForeignRates = rates.data;
    });};

this.add = function () {
    this.counter = this.counter + 1;
};

this.getRate = function getRate(curr){
    return this.usdToForeignRates[curr];
};

this.total = function total(outCurr) {
    var result = this.qty * this.cost * this.usdToForeignRates[outCurr] / this.usdToForeignRates[$scope.inCurr];
    return result;
};
this.pay = function pay() {
    window.alert("Paid!");
};
}]);

1 个答案:

答案 0 :(得分:2)

if (t > max_t) // t is time index // compress array by 1/2 for (i = 0 to arraySize) a[i] = (a[i * 2] + a[i * 2 + 1]) / 2; // start from mid-point t = arraySize / 2; [ re-plot the graph from 0 to 1/2 arraySize ] else [ plot the next datum normally ] ++t 函数中的这是then promise上下文。您需要对控制器http的引用。尝试

'this'