如何在AngularJS中从JSON读取数据后更新模型

时间:2016-06-21 13:40:06

标签: javascript angularjs json

我正在尝试在AngularJS中编写应用程序,并且在某些时候我通过表单更新我的数据:

<h3> Anzeige </h3>

<form name="anzeige-form" ng-controller="AnzeigeController as anzCtrl" ng-submit="anzCtrl.getMyOrder()">
    <label for="id">Meine Bestellnummer</label><input type="text" required class="form-control" id="id" ng-model="anzCtrl.id" placeholder="0..X" />
    <button type="submit" class="btn btn-default">Laden / Aktualisieren</button>


<div class="ausgabe">
Ihre Adresse : {{anzCtrl.myorder.order.address}}
<ul class="list-unstyled anzeige">
    <li class="list-item" ng-repeat="pizza in anzCtrl.myorder.order.cart">
        <h3>{{pizza.name}}</h3><br/>
        <span class="status" ng-if="pizza.status=0">Bestellt</span>
        <span class="status" ng-if="pizza.status=1">Im Ofen</span>
        <span class="status" ng-if="pizza.status=2">Lieferbereit</span>
        <span class="status" ng-if="pizza.status=3">Unterwegs</span>
        <span class="status" ng-if="pizza.status=4">Lieferbereit</span>
        <div class="progress">
            <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="{{pizza.status}}" aria-valuemin="0" aria-valuemax="4" style="width: {{pizza.status * 25}}%">
                <span class="sr-only">{{pizza.status * 25}}% Abgeschlossen</span>
            </div>
        </div>
    </li>
</ul>
</div>
</form>

Angular Code看起来像这样:

.controller('AnzeigeController',function($http){

    //$scope.adress = '';
    this.id = 21;
    //this.myorder = order2;
    this.myorder = {};
    //$scope.myarray = {};

    this.getMyOrder = function(){

        $http.get('get_by_id.php',{params:{"id": this.id}}).success(function(datar){

            this.myorder = angular.fromJson(datar);
            console.log(this.myorder);
        })
    }
})  

我的问题是现在,我不知道如何告诉Angular发生了异步更新,我的List将使用正确的值进行更新。记录myorder变量会在调试器/控制台中为我提供正确的对象。

我主要不了解如何访问数据,因为行{{anzCtrl.myorder.order.address}}没有显示任何内容。

我有一个主要的思考错误是我的猜测。 请说明如何正确地做到这一点。

最诚挚的问候,Marc

1 个答案:

答案 0 :(得分:0)

问题是当你的诺言结算时this不再引用控制器模型。您需要创建另一个变量来保存this,然后在您的承诺结算时使用此其他变量。

.controller('AnzeigeController', function($http) {
    var _this = this;
    _this.id = 21;
    _this.myorder = {};

    _this.getMyOrder = function() {
        $http.get('get_by_id.php',{params:{"id": _this.id}}).success(function(datar){
            _this.myorder = angular.fromJson(datar);
            console.log(_this.myorder);
        })
    }
})