Reputation: 521
I'm having an issue where although my Angular JS is returning data from my backend, I can't get ng-repeat to display it. Here's my HTML file:
<!DOCTYPE html>
<html ng-app="docManager">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="DocManCtrl as docs">
<div>
<input placeholder="Search" type="text" ng-model="searchKey" />
</div>
<table class="table">
<tr><th>Document ID</th><th>Filename</th><th>Category</th></tr>
<tr ng-repeat="document in docs.documents | filter:searchKey">
<td>{{document.id}}</td>
<td>{{document.filename}}</td>
<td>{{document.category}}</td>
</tr>
</table>
<button ng-click="docs.add()">Add Document</button>
</body>
And here is my JS file:
var app = angular.module('docManager', []);
app.controller('DocManCtrl', DocManCtrl);
function DocManCtrl($http){
$http.get('http://localhost:3000/documents').success(function(data){
this.documents = data;
console.log('Data retrieved.');
}).error(function(){
console.log('Error: could not GET documents');
});
}
DocManCtrl.prototype.add = function(){
console.log('Hello, world.');
};
I know my $http.get is working, because if I print out the contents of 'data' to the console, I see the data from my database. Anybody know where my mistake is?
Thanks! Bryan
Upvotes: 3
Views: 528
Reputation: 3319
var app = angular.module('docManager', []);
app.controller('DocManCtrl', DocManCtrl);
function DocManCtrl($http){
var vm = this;
$http.get('http://localhost:3000/documents').success(function(data){
vm.documents = data;
console.log('Data retrieved.');
}).error(function(){
console.log('Error: could not GET documents');
});
}
DocManCtrl.prototype.add = function(){
console.log('Hello, world.');
};
Upvotes: 1
Reputation: 18523
When you use this
in your callback function it doesn't refer to your controller. So you'd have to do something like this:
function DocManCtrl($http) {
var self = this;
$http.get('http://localhost:3000/documents').success(function (data) {
self.documents = data;
});
}
Upvotes: 4