javascript - 加载指令时调用 init 函数

标签 javascript html angularjs html-parsing angularjs-ng-init

我有一个简单的指令,可以从服务 (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);
                        });


                };


            }
        }
    })

加载的评论应该使用ng-init加载到列表(在templateUrl中)然后加载服务(如果需要我会添加代码) .

<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>

该指令在其范围内具有 loadCommets() 函数,但未触发。 感谢您的帮助!

最佳答案

我建议将函数调用放在链接函数本身而不是 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();
            }
        }
    })

编辑:顺便说一下,您的 forEach 语法是错误的。应该是

angular.forEach(response, function(comment){
    $scope.comments.push(comment);
});

关于javascript - 加载指令时调用 init 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33342437/

相关文章:

javascript - 带有数据的 Angular 提交表

javascript - JQuery 只查看一个 DIV ID 来获取值

javascript - javascript如何避免 anchor 标记中的文本

javascript - 使用 CSS 的绝对大小

html - 如何修复与另一个元素内联的元素,而不管前一个元素的大小

javascript - ngGrid 对整个结果集进行排序

javascript - javascript如何获取其他网站的数据?

javascript - 当每个节点的子节点数大于 5 时,图形飞出屏幕

php - PHP 管理员登录问题

javascript - Angular ng-show 无法正常工作