简体   繁体   中英

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!

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" />

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM