10

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
  • 5,777
  • 10
  • 35
  • 55

1 Answers1

19

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.

rtucker88
  • 986
  • 8
  • 15
  • 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. – charliebrownie Nov 02 '14 at 22:14
  • I used this approach with no success until I finally used `$scope.$apply();` after which the ng-repeat was fulfilled. – ThisClark Jul 13 '17 at 05:02