我正在使用 Angular 1.3,我已经将我的代码更改为使用 Controller as
$scope。我有一个网址:
http://localhost:3640/api/v1/topics
这将得到以下 json:
[
{
topicId: 17,
title: "This is another BRAND SPANKIN new topic",
body: "This is a message in the body of another topic ftw!",
created: "2014-11-27T05:37:49.993",
replies = null
},
{
topicId: 18,
title: "This is another BRAND new topic",
body: "This is a message in the body of a topic wow!",
created: "2014-11-27T05:37:49.993",
replies = null
}
]
我还有一个名为索引主页的页面.js
var app = angular.module("myApp", []);
app.controller("homeIndexController", ["$http", function ($http) {
var msg = this;
msg.dataCount = 0;
msg.replies = [];
$http.get("/api/v1/topics?includeReplies=true")
.success(function(data) {
//Success
msg.replies = data;
})
.error(function() {
//Error
alert('error/failed');
});
}]);
在我的页面上,我使用以下绑定:
<div id="ngController" ng-controller="homeIndexController as hic">
...
<h3>Message count: {{hic.dataCount}}</h3>
...
<div class="message row" data-ng-repeat="i in hic.data">
<div class="title">{{i.title}}</div>
<div class="date">{{i.created}}</div>
<div class="contents">{{i.body}}</div>
</div>
我知道$http中的 url 正在工作,因为我在浏览器和小提琴手中自行尝试了它,它返回了 json。但是当我在我的角度应用程序中使用它时,我得到 .error 结果(这是一个说 FAIL 的警报。
我尝试删除http://localhost:3640
,并且仅在执行此操作时使用/api/v1/topics
,我不再得到错误结果。我知道我的控制器正在工作并绑定到页面,因为我在dataCount
得到 0 .
我在$http
方法中做错了什么?我的语法有误吗?
错误出在您的 ng-repeat 属性中。您的作用域中没有数据变量。将hic.data更改为hic.replies,它将起作用。
<div id="ngController" ng-controller="homeIndexController as hic">
...
<h3>Message count: {{hic.dataCount}}</h3>
...
<div class="message row" data-ng-repeat="i in hic.replies">
<div class="title">{{i.title}}</div>
<div class="date">{{i.created}}</div>
<div class="contents">{{i.body}}</div>
</div>
好吧,伙计,这是一个真正的菜鸟错误,看看你的控制器:
app.controller("homeIndexController", ["$http", function ($http) {
var msg = this;
msg.dataCount = 2;
msg.replies = [];
$http.get("/api/v1/topics")
.success(function(data) {
//Success
msg.replies = data;
})
.error(function() {
//Error
alert('eror/failed');
});
}])
您将this
设置为 msg
,然后将msg.replies
设置为等于data
如果成功。
这没关系。
然后,当您说以下内容时,您的问题就会出现在您的ng重复中:
<div data-ng-repeat="i in hic.data">
hic.data
不存在。 data
是从$http.get
.success(function())
返回的物品。然后,您将该data
分配给msg.replies
。因此,您的ng-repeat=""
应如下所示:
<div data-ng-repeat="i in hic.replies">
理解?这是基本的东西...我,呃,我的意思是你应该觉得自己很傻。