[英]How to send data to view from controller AngularJS
I want to send data from api to my view... So I need to take data from get reqest and then send that data to my view on my page. 我想将数据从api发送到我的视图...所以我需要从get reqest获取数据,然后将该数据发送到我的页面上的视图。
Here is my controller: 这是我的控制器:
angular.module('commentsApp',['notifications'])
.config(function($routeProvider,$locationProvider) {
$routeProvider.
when('/project/:id', {
controller: 'CommentsCtrl',
template: '<%comments%>'
}).
otherwise({
template: 'aaaaaaa',
redirectTo: '/'
});
})
.controller('CommentsCtrl',function($scope,$http,$routeParams){
$scope.comments = [];
$scope.param = $routeParams.id;
$http.get("/api/comments/"+ $scope.param)
.success(function(data){
$scope.comments = data;
})
.error(function(data){
console.log(data);
});
});
Here is my html: 这是我的html:
<div id="comment" ng-app="commentsApp" class="panel-body">
<div ng-view>
<h1><% ng %></h1>
</div>
</div>
You should be declaring your ng-app
in the <html>
tag. 您应该在<html>
标签中声明您的ng-app
。 I'm not sure what the <% ng %>
is, nor the <% comments %>
in your template, but that is not how angular renders data to the view. 我不确定模板中的<% ng %>
是什么,也不确定<% comments %>
,但这不是角度如何将数据呈现到视图中。 Since comments is an array, you'll want to use an ng-repeat
to display the data. 由于注释是一个数组,因此您需要使用ng-repeat
来显示数据。
Something like (in your template) 类似于(在您的模板中)
<ul>
<li ng-repeat="comment in comments">
{{comment}}
</li>
</ul>
The {{comment}}
is how angular renders variables, similar to erb's <%= comment %>
. {{comment}}
是角度渲染变量的方式,类似于erb的<%= comment %>
。 Comment, is a local variable for each <li>
that gets generated by the ng-repeat
, which gets its data from the $scope variable comments
. Comment是ng-repeat
生成的每个<li>
的局部变量,它从$ scope变量comments
获取数据。
EDIT: Also you may need to $scope.$apply();
编辑:另外,您可能需要$scope.$apply();
in your CommentsController after you assign $scope.comments = data
. 在分配$scope.comments = data
之后,在CommentsController中。 Not sure on this point, I haven't got angular's full digest cycle in my head yet. 在这一点上不确定,我还没有获得angular的完整摘要周期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.