2

What I'm trying to show the contents of ng-repeat after calling AJAX (i.e. $http)

    <table ng-controller="TableController as tc">
        <tr>
            <th>Date</th>
            <!-- other headers are here -->
        </tr>
        <tr ng-repeat="order in tc.orders" >
            <td ng-bind="order.id"></td> //It doesn't appear
            <td>@{{ order.id }}</td>     //It doesn't appear as well. I use Laravel, so I need to put @
        </tr>
    </table>

Here is the relevant script part

angular.module('adminAngular', ['ui.bootstrap','dialogs.main'])
.controller('TableController', function(dialogs, $http){

    var instance = this;
    this.orders = [];
    $http({
        method : "POST",
        url : "/admin/getOrders"
    }).then(function (response) {
        this.orders = response.data;
        console.log("Inside; "+this.orders.length);
        });
});

From console.log("Inside; "+this.orders.length), I can see that the expected data was assigned to this.orders array. However, as the title of this post suggests, the array is not displayed with ng-repeat="order in tc.orders".

I followed this question, but following this did not solve this issue. Now I suspect that the cause lies in the as statement, which I have to use for this occasion.

As I don't see many information resources about the as online, I'd appreciate if you'd give any advice.

Community
  • 1
  • 1
Hiroki
  • 3,893
  • 13
  • 51
  • 90
  • You could set a boolean flag and do something like `ng-show=retrievedData` – Jeremy Jackson Apr 13 '16 at 03:45
  • 2
    Use `instance.orders = response.data` in your `then()` handler. `this` in that context refers to the `function(response) {...}`, not your controller – Phil Apr 13 '16 at 03:45
  • Possible duplicate of [How to access the correct \`this\` / context inside a callback?](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) – Phil Apr 13 '16 at 03:46

1 Answers1

1

you should use your instance inside promise resolved function to assign to the right instance (controller instance) :

angular.module('adminAngular', ['ui.bootstrap','dialogs.main'])
.controller('TableController', function(dialogs, $http){
var instance = this;
instance.orders = [];
$http({
    method : "POST",
    url : "/admin/getOrders"
}).then(function (response) {
    instance.orders = response.data;
    console.log("Inside; "+ instance.orders.length);
        });
});

its usual to name this instance : vm refers to View Model

Example:

angular.module('adminAngular', ['ui.bootstrap','dialogs.main'])
.controller('TableController', function(dialogs, $http){
var vm= this;
vm.orders = [];
$http({
    method : "POST",
    url : "/admin/getOrders"
}).then(function (response) {
    vm.orders = response.data;
    console.log("Inside; "+vm.orders.length);
    });
});
Ahmad Mobaraki
  • 7,426
  • 5
  • 48
  • 69