Vladimir Djukic Vladimir Djukic - 2 months ago 10
AngularJS Question

How to push objects in AngularJS right below the element

I have recusativ tree... I get it from laravel api. Problem is when I push object it don't go below the comment I want reply, it go on the end.

Here is my directive:

el
is current element inside
ng-repeat
, I need below that element to add new one.

This part:
scope.comments.push(data);
will push element on the end of
ng-repeat


.directive("addreplys", function($compile,commentFactory){
return {
link: function (scope, element, attrs) {

// I contain the ngModel values for form interaction.
scope.form = {
reply: ""
};

//CALL FACTORY TO ADD NEW REPLAY
scope.addReply = function(el) {

commentFactory.saveComment(scope.form.reply[el.pivot.comment_id],el.pivot.project_id,el.pivot.comment_id,el.level+1)
.success(function(data){
//ADD REPLY TO CLIENT SIDE
scope.comments.push(data);
})
.error(function(data){
console.log(data);
});
// Reset the form once values have been consumed.
scope.form.reply = "";
};
}
};
});


Any solution?

Answer

push always pushes items to the end of an array. use unshift instead of push

Ok, then look: 1. find the index "idx" of the current document in the array:

allComments.indexOf(currentDocument)

  1. splice the the newObject into the array

allComments.splice(idx + 1, 0, newObject)

finalCode

allComments.splice(allComments.indexOf(currentDocument) + 1, 0, newObject)
Comments