[英]How to send data to view from controller AngularJS
我想将数据从api发送到我的视图...所以我需要从get reqest获取数据,然后将该数据发送到我的页面上的视图。
这是我的控制器:
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);
});
});
这是我的html:
<div id="comment" ng-app="commentsApp" class="panel-body">
<div ng-view>
<h1><% ng %></h1>
</div>
</div>
您应该在<html>
标签中声明您的ng-app
。 我不确定模板中的<% ng %>
是什么,也不确定<% comments %>
,但这不是角度如何将数据呈现到视图中。 由于注释是一个数组,因此您需要使用ng-repeat
来显示数据。
类似于(在您的模板中)
<ul>
<li ng-repeat="comment in comments">
{{comment}}
</li>
</ul>
{{comment}}
是角度渲染变量的方式,类似于erb的<%= comment %>
。 Comment是ng-repeat
生成的每个<li>
的局部变量,它从$ scope变量comments
获取数据。
编辑:另外,您可能需要$scope.$apply();
在分配$scope.comments = data
之后,在CommentsController中。 在这一点上不确定,我还没有获得angular的完整摘要周期。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.