Why doesn't JSON data load immediately in my HTML page?

229 views Asked by At

This is my controller, that takes JSON data to Wordpress :

app.controller('AboutController', function($scope, $http) {

$scope.device=device;
var page_id = 2;

$.ajax({
        url: 'http://davidemilone.com/provawp/?json=get_page&page_id='+page_id+'&callback=?',
        dataType: 'jsonp',
        type: 'GET',
        success: function(data) {

                $scope.page=data.page;
                console.log("contenuto" + $scope.page.content);
        }
});
});

Now, this is my HTML page:

<ons-page ng-controller="AboutController" >
  <ons-toolbar modifier="opacity">
    <div class="left">
      <ons-toolbar-button ng-click="menu.toggle()"><ons-icon icon="ion-navicon-round" fixed-width="false"></ons-icon></ons-toolbar-button>
    </div>
    <div class="center">{{page.title}}</div>
  </ons-toolbar>

  <div class="app-page-content">
    <p class="page-content" ng-bind-html="page.content"></p>
  </div>

Why data doesn't load immediately, it loads only after I click back or when carousel auto slide; what I am doing wrong?

1

There are 1 answers

8
Tomek Sułkowski On BEST ANSWER

You're not using Angular's own tools (e.g. $http service) to comunicate with the server, so the framework doesn't know that the data has changed.

To let Angular know that something on $scope has changed in non-angular way, you should run $scope.$apply(); after you assign the new data.

(To explain the "clicking outside" part: it simply triggers the digest loop - same result as $apply(), that's why the value was updating then)

It would be preferable to use $http service though. I can see you've already injected it into the controller, so it may be a simple mistake, that you used jQuery's ajax function insted. (see Angular docs for $http service for details)

app.controller('AboutController', function($scope, $http) {
    $scope.device=device;
    var page_id = 2;

    var url = 'http://davidemilone.com/provawp/?json=get_page&page_id='+page_id+'&callback=?';
    $http.jsonp(url).then(function(response) {
        console.log(response.data);
        $scope.page = response.data.page;
    });

});