![](/img/trans.png)
[英]AngularJS view doesn't update when assigning a $http response to $scope
[英]AngularJS : View doesn't update when a value in $scope changes
我有一個帶有視圖的html文件,它從AngularJS范圍獲取它的值。
<form ng-controller="EmployeesController as emp" class="signed-in" ng-submit="logOutUser()">
<div class="row">
<div class="col-md-10 text-left">
<h5>Your Games, {{emp.username}}</h5>
</div>
<div class="col-md-2">
<button class="btn btn-md btn-primary btn-block" type="submit">Log Out</button>
</div>
</div>
<div class="row store">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">Games To Buy</div>
<div class="panel-body">
<table class="table table-striped">
<thead>
<tr>
<th>Game Name</th>
<th>Game Status {{what}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="game in emp.games">
<td>{{game}}</td>
<td>
<button ng-click="buyGame(game.gameId)" type="button" class="btn btn-sm btn-primary btn-block" href="#">Buy</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</form>
。
和js文件:
var app = angular.module("MyApp", ['ngRoute']);
app.controller("EmployeesController", function($scope, $http) {
this.games = [{gameName: 'aaa', gameId: '1'},{gameName: 'aaa', gameId: '1'},{gameName: 'aaa', gameId: '1'}];
this.ownedGames = [];
var that = this;
$scope.sellGame = function(gameId) {
var index = that.ownedGames.indexOf(gameId);
that.ownedGames.splice(index, 1);
$.jStorage.set(that.username, that.ownedGames);
}
$scope.$on('$viewContentLoaded', function() {
if($.jStorage.get('Employee') == null)
$scope.logged = false;
else
$scope.logged = true;
$http.get('employees.json').
success(function(data, status, headers, config) {
that.games = data.games;
that.username = $.jStorage.get('Employee');
if($.jStorage.get(that.username) != null)
that.ownedGames = $.jStorage.get(that.username);
});
});
});
好。 基本上問題是, emp.games
變量是空的。 首先,它在呈現的HTML頁面中被注釋,第二,當我調試頁面時,變量emp.games
為空。 然而,emp.games應該從其獲取其值的變量,$ scope.games充滿了應有的值。 所以問題是我的emp.games
沒有看到$ scope.games在該http請求中被更新,因此IT不會更新。 我盡可能多地用Google搜索,發現我應該使用$ scope.apply,但無論我在哪里使用它,我都會收到錯誤$ digest正在進行中......有什么想法嗎?
謝謝
嘗試檢查diggest
if (!$scope.$$phase) {
$scope.$apply(function () {
that.games = data.games;
})
}
else
that.games = data.games;
或者你可以注入$ timeout服務並像這樣使用它,它會更好。
$timeout (function () {
that.games = data.games;
}, 0)
您的控制器定義無效,請使用這樣的。
app.controller("EmployeesController", ['$scope','$http','$timeout', function($scope, $http, $timeout){
//....
}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.