-1

I have an issue in AngularJS on using $http to fetch data from server. Here is my HTML

<select ng-model="foo" ng-options="item as item.name for item in items"></select>

Here is my AngularJS Script

angular.module("myApp").controller("myCtrl", function($scope, $http) {
    var $scope.items = [];
    $scope.items = [
        {
            "id": 1,
            "name": "item1"
        },
        {
            "id": 2,
            "name": "item2"
        },
    ];

    getData();

    function getData() {
        $http.get("ng/getData")
            .then(function(response) {
                if (response.status == 200) {
                    $scope.items = response.items;
                    /*
                    $scope.items = [
                        {
                            "id": 5,
                            "name": "item11"
                        },
                        {
                            "id": 4,
                            "name": "item22"
                        }
                    ];
                    */
                }
            });
    }
});

What expect from this code is when $http fetches data from server, then select dropdown data will change. But it's not changing anything. I have also printed the response items in the console inside the success callback.

Maybe I don't understand $http usage well enough. Perhaps when I console out data after getData(); $scope.items doesn't change at all. And I think that maybe $http always run at last stage.

Can anybody help to explain this issue? If my assumption is correct, what is the solution that I am looking for?

Christian Neverdal
  • 5,655
  • 6
  • 38
  • 93
Friday
  • 1
  • 1
  • 2
  • 2
    did you check if you pass in the `then` callback ? furthermore data from response are stored under `response.data` so you should have `$scope.items = response.data.item` – Walfrat Apr 22 '16 at 09:55

2 Answers2

0

I think you simply have to add a track by clause:

ng-options="item as item.name for item in items track by item.id"
MarcoS
  • 17,323
  • 24
  • 96
  • 174
0

Check the response object. When you are using 'then' callback to get the resolved data then the actual API result is stored in the 'data' property of the response. So change your code to

$scope.items = response.data;

Or you can use the success callback to attach the data directly.

        $http.get("ng/getData")
            .success(function(response) {
                if (response.status == 200) {
                    $scope.items = response.items;
                }
            });
Pratik Bhattacharya
  • 3,596
  • 2
  • 32
  • 60