benbenben
benbenben

Reputation: 159

View is not updated after $http.get

I know there has been a lot of posts on this and I've tried their solutions but it still does not work.

Basically I need to get a list of countries from my database and display it on the html page on document load

Below is my controller

$scope.country_options = [];

function get_countries() {
  var url = "/dashboard-api/api/country/";
  var defer = $q.defer();

  $http.get(url)
    .then(function(response) {
      defer.resolve(response.data.result);
    });

  return defer.promise;
}

function init() {
  var promise = get_countries();
  promise.then(function(data) {
    $scope.country_options = data;
  })
  console.log($scope.country_options);
}

init();

And on my html page

<input class="form-check-input" type="checkbox" ng-repeat="item in country_options" value="item.country_code"
       ng-model="country[item.country_code]">
&nbsp;{{item.name}}

Your help is much appreciated! Thank you!

Upvotes: 0

Views: 42

Answers (2)

Shohel
Shohel

Reputation: 3934

Try to use:

$timeout( function(){ 
   $scope.country_options = data
}, 0);

Input value

value="{{item.country_code}}"

Bind the text box by the following way:

<input type ="text" ng-bind="item.country_code" />
or
<input type="text" ng-value="item.country_code" />
or
<input type="text" value="{{item.country_code}}" />
or
<input type="text" ng-model="item.country_code" />

Upvotes: 1

Parth Savadiya
Parth Savadiya

Reputation: 1211

You need to use $scope.$apply() function so replace $scope.country_options = data line with below code

$scope.$apply(function() {
  $scope.country_options = data
});

Upvotes: 0

Related Questions