我遇到了一个问题,虽然我的Angular JS从我的后端返回数据,但我无法通过ng-repeat来显示它。这是我的HTML文件:
<!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>
这是我的JS文件:
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.');
};
我知道我的$ http.get正在运行,因为如果我将'data'的内容打印到控制台,我会看到数据库中的数据。有谁知道我的错误在哪里?
谢谢! 布赖恩
答案 0 :(得分:4)
在回调函数中使用this
时,它不会引用您的控制器。所以你必须做这样的事情:
function DocManCtrl($http) {
var self = this;
$http.get('http://localhost:3000/documents').success(function (data) {
self.documents = data;
});
}
答案 1 :(得分:1)
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.');
};