Shreesh Katyayan
Shreesh Katyayan

Reputation: 111

AngularJS: Add event listener after .post()

I am trying to learn development, so sorry if I am a bit uninformed. I tried searching here for solutions. I have to make a comment and reply app. I am using this function to add comments to my view.

$scope.insertComment = function(){

    var new_comment_id = $scope.comments[$scope.comments.length - 1].commentID +1;
    var input = {
        "commentID" : new_comment_id,
        "userID": user.user_id,
        "name": user.user_name,
        "avatar_url": user.avatar,
        "says": $scope.new_comment,
        "likes": 0,
        "like_status": false,
        "replies": [] 
    };
    //Pushes changes to the global comment object
    $scope.comments.push(input);
    $scope.new_comment = '';
}

Each comment has reply option, with following event which displays a form to add reply to the comment.

$(".no-url").click(function(){
    console.log('test2');
    $(this).parent().children('.reply-form').addClass('active');
});

My problem is that when I add a new comment, it doesn't have this event listener associated with it. How to solve this?

Upvotes: 1

Views: 1110

Answers (3)

maurycy
maurycy

Reputation: 8465

Here is simplified code how to do it with just angularjs without involving jQuery

<div class="comment" ng-repeat="comment in comments track by $index>
  <p>{{comment.text}}</p>
  <button ng-click="comment.reply = true">reply to comment</button>
  <form ng-if="comment.reply">
    <textarea ng-model="reply"></textarea>
    <button ng-click="submitReply()">submit reply</button>
  </form>
</div>

Upvotes: 1

Rayon
Rayon

Reputation: 36609

$(SELECTOR) will select only those elements which are present in the DOM.

Event-Delegation could be used

$(PARENT_SELECTOR).on('click', '.no-url', function() {
  $(this).parent().children('.reply-form').addClass('active');
});

But better and recommended solution will be to use ng-click directive.

Upvotes: 1

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

Use directive with jQLite

HTML :

 <div comment-click> 
    //your comment html will goes here.
 </div>

JS:

app.directive("commentClick",function(){

    return {
        link : function(scope,ele,attr){

            ele.on('click',function(){

                //put here your commnet scropt

            })
        }
    }
})

Add this comment-click attribute to your ever new added DOME element on which you want to bind the click event

Upvotes: 1

Related Questions