binding data from $http.get() request into ng-repeat

19,487

You're mixing up the controller as syntax and using scope. See my plunker at http://plnkr.co/qpcKJZx4jovC6YdzBd6J and you'll see an example.

The main change is when using controller as syntax you need to bind your variables to this.

app.controller('MyController', function($http) {
    var vm = this;
    vm.mydata = [];

    $http.get(URI)
        .then(function(result) {
          console.log(result);
          vm.mydata = result.data;
         });

Choose one method of publishing your view data and stick with it, either controller as or $scope.

You will notice the top "Data from server" is no longer working in the plunker, because I did not change that one to use the controller as syntax.

Share:
19,487

Related videos on Youtube

charliebrownie
Author by

charliebrownie

I am a Software Engineer with strong interest in: Clean Code and good practices the whole Software Development Process Web Development & Technologies "Life is about creating yourself." "Do what you love, love what you do."

Updated on June 04, 2022

Comments

  • charliebrownie
    charliebrownie almost 2 years

    I'm getting fine my JSON data from a server, but the problem comes when trying to list it at my page using the ng-repeat directive.

    Here's my HTML body content, where 'mydata' (JSON array) is shown correctly as soon as the $http.get() method receives the data requested, but the ng-repeat is not listing the array elements:

    <body ng-app="myapp">
      <div ng-controller="MyController" >
        Data from server: {{ mydata }}          
      </div>
    
      <hr>
    
      <ul ng-controller="MyController as controller">
        <li ng-repeat="data in controller.mydata">
          {{ data }}
        </li>
     </ul>
    </body>
    

    And here is the Javascript code:

    var URI = 'http://my_service_uri/';
    
    angular.module("myapp", [])
        .controller("MyController", function($scope, $http) {
            $scope.mydata = [];
    
            $http.get(URI)
                .then(function(result) {
                    $scope.mydata = result.data;
                 });
        });
    
  • charliebrownie
    charliebrownie over 9 years
    Thank you for the answer, is working perfectly right now. I see what I was doing wrong, and thank you for the advice, I'll stick to one method of publishing the view data, either controller as or $scope.
  • ThisClark
    ThisClark almost 7 years
    I used this approach with no success until I finally used $scope.$apply(); after which the ng-repeat was fulfilled.