Reputation: 681
I made the below code to learn Angular. It uses the input entered by user to make an ajax request for a json file that contains a list of object, then print that list to the user.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script type="text/javascript">
angular.module('myApp', [])
.controller('myController', function($http) {
var ctlr = this;
ctlr.param = "";
ctlr.responses = [];
this.makeQuery = function() {
$http.get('http://localhost:8080?p=' + ctlr.param))
.then(function(data) {
ctlr.response = data; // data -> [{key1: value1,...},...]
});
};
});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="myController as mc">
<input type="text" ng-model="mc.param">
<input type="submit" ng-click="mc.makeQuery()" value="Submit">
<ul>
<li ng-repeat="res in responses">
<span>{{res.key1}}, {{res.key2}}</span>
</li>
</ul>
</div>
</body>
</html>
When I run this code in Chrome, I see a list of empty bullet points. Chrome DevTools shows the json file returned as expected so I know ctlr.param
works. However the list has empty bullet points so ng-repeat
does not work correctly. It seems I cannot access cltr.responses
properly. Does anyone know why?
Upvotes: 0
Views: 57
Reputation: 713
Above solution is right but as i checked the complete code and found that there is one mistake. In script code
ctlr.response = data; // data -> [{key1: value1,...},...]
should be
ctlr.responses = data; // data -> [{key1: value1,...},...]
Upvotes: 0
Reputation: 15292
Your responses
object is binded to this
and not to $scope
as you are using controller as
You should use mc.responses
instead of responses
<li ng-repeat="res in mc.responses">
<span>{{res.key1}}, {{res.key2}}</span>
</li>
You can read more from johnpapa style
Upvotes: 4