简体   繁体   中英

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.

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:

<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. 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. Since comments is an array, you'll want to use an ng-repeat to display the data.

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, is a local variable for each <li> that gets generated by the ng-repeat , which gets its data from the $scope variable comments .

EDIT: Also you may need to $scope.$apply(); in your CommentsController after you assign $scope.comments = data . Not sure on this point, I haven't got angular's full digest cycle in my head yet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM