1

這很可能很簡單,但仍然如此。我在我的控制器中有一個http調用,我加載了一個json文件。我想根據結果更新我的html中的變量。它顯然更新JS中的變量(console.log),但不是在html中。 有沒有辦法使用$ apply的結果或類似的?還有什麼可以使用的? 這裏有一個(not) working plnkr更新角度爲http請求的回調變量

JS:

function SomeController($http){ 
    this.someValue = 'initial'; 
    $http.get('test.json').then(function (data) { 
    this.someValue="changed"; 
    console.log("get request "+this.someValue); 
    }); 
} 

app.controller('someController', SomeController); 

HTML:

<div ng-controller="someController as some"> 
     <p>{{some.someValue}}</p> 
    </div> 

回答

1

每當我們創造它有自己的this(上下文)的功能。在你的情況this你正在使用裏面$http.get成功函數不是this(上下文)的SomeController函數。您必須保留函數上下文self變量&然後在您的成功回調函數$http.get函數中使用該變量,以便this將被視爲全局變量。

控制器

function SomeController($http){ 
    var self =this; 
    self.someValue = 'initial'; 
    $http.get('test.json').then(function (data) { 
    self.someValue="changed"; 
    console.log("get request "+this.someValue); 
    }); 
} 

Demo Plunkr

0

thiscontroller$http是不同的,因爲他們是在範圍不同塊,以便在其他變量分配this_this並使用它。

試試吧

function SomeController($http){ 
    var _this = this; 
    _this.someValue = 'initial'; 
    $http.get('test.json').then(function (data) { 
    _this.someValue="changed"; 
    console.log("get request "+_this.someValue); 
    }); 
}