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;
});
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With