Invocation of init function when loading directive

I have a simple directive that loads service ( commentsService) comments :

'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);
                        });


                };


            }
        }
    })

Downloaded comments should be uploaded to the list (inside templateUrl) using ng-init, and then a service for downloading (I will add code if necessary).

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

The directive has a function in its scope loadCommets(), but it does not start. Thank you for your help!

+4
source share
1 answer

I suggest placing a function call inside the link function itself instead of 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();
            }
        }
    })

Edit: By the way, your forEach syntax is incorrect. It should be

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

Source: https://habr.com/ru/post/1613169/


All Articles