加载指令时调用init函数

Its*_*has 4 html javascript html-parsing angularjs angularjs-ng-init

我有一个简单的指令来加载来自service(commentsService)的注释:

'use strict';

angular.module('mean.rank')
    .directive('commentList', function(CommentsService, Global) {
        return {
            restrict: 'E',
            templateUrl:  'rank/views/comments-list.html',
            replace: false,
            link: function($scope, element, attrs) {
                //accessing the ad info :  console.log("ADD  " , $scope.ad);
                $scope.comments = [];

                $scope.loadComments = function () {
                    console.log("in loadComments");
                    var adID = {};
                    adID.ad_ID = $scope.ad.nid;
                    console.log("calling services.getComments function with  " , adID.ad_ID);
                    CommentsService.getComments(adID.ad_ID)
                        .then(function (response) {
                            angular.forEach(comment in response)
                            $scope.comments.push(comment);
                        });


                };


            }
        }
    })
Run Code Online (Sandbox Code Playgroud)

加载的注释应该加载到列表(在里面templateUrl)使用ng-init然后加载服务(如果需要,我将添加代码).

<div ng-init="loadComments()">
    <ul class="media-list comment-detail-list" >
        <li class="media" ng-repeat="comment in comments" >
            <article>
                <div class="pull-left comment-info">
                    <a href="#" class="author">{{ comment.author }}</a><br />
                    <time>{{ comment.datePublished | date:"MM/dd/yyyy" }}</time>
                </div>
                <div class="media-body">
                    <div class="comment-body">
                        <p>{{ comment.comment }}</p>
                    </div>
                </div>
            </article>
        </li>
        <li>Debugger</li>
    </ul>
</div>
Run Code Online (Sandbox Code Playgroud)

该指令在其范围内具有该loadCommets()功能但不会被触发.谢谢你的帮助!

Icy*_*ool 5

我建议将函数调用放在链接函数本身而不是ng-init中.

angular.module('mean.rank')
    .directive('commentList', function(CommentsService, Global) {
        return {
            ...
            link: function($scope, element, attrs) {
                //accessing the ad info :  console.log("ADD  " , $scope.ad);
                $scope.comments = [];

                $scope.loadComments = function () {
                    ...
                };

                $scope.loadComments();
            }
        }
    })
Run Code Online (Sandbox Code Playgroud)

编辑:顺便说一下你的forEach语法是错误的.它应该是

angular.forEach(response, function(comment){
    $scope.comments.push(comment);
});
Run Code Online (Sandbox Code Playgroud)