1

これはおそらく簡単ですが、私はjsonファイルをロードする私のコントローラにhttp呼び出しを持っています。結果に基づいてHTML内の変数を更新したいと思います。 JS内の変数(console.log)は明らかに更新されますが、htmlでは更新されません。 $ applyを結果などに使用する方法はありますか?他に何を使用するのですか?我々はそれが自身のthis(コンテキスト)を持っている関数を作成するたびにhttp要求コールバックの変数を更新します。

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

答えて

1

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: はここ(not) working plnkr

JSです。あなたのケースではthis内部で$http.get成功関数はthis(文脈)SomeControllerの機能を使用していない使用しています。 SomeController関数のコンテキストをself変数&のままにして、$http.get成功コールバック関数でその変数を使用して、thisをグローバル変数として扱う必要があります。彼らはスコープの異なるブロックにあるため

コントローラは、あなたのcontroller

0

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$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); 
    }); 
} 
それを試してみてください
関連する問題