0

I have a requirement to render all the posts from my database by using AngularJS. I need to provide Edit functionality for each post that is visible to the user. Currently, I am doing this by using a 'edit-post' directive. Here is the linking function for that.

link: function ($scope, element, attrs) {
            element.bind('click', function () {
                var divId = $scope.$parent.post.meta.id + "Data";

                var html = $compile("<div class='editTextAreaDiv' id='" + divId + "'>" +
                            "<textarea  class='editTextArea' id='editBox' rows='3' ng-model='editedPostText' name='editedPostText'>" + $scope.$parent.post.meta.data + "</textarea><br />" +

                            "<span class='pull-right'>" +
                                "<input class='btn' type='button' value='Save'  ng-click='saveEditedPost(\"" + divId + "\")'/>" +
                                "<input class='btn' type='button' value='Cancel' ng-click='cancelEdit(\"" + divId + "\")'/>" +
                            "</span>" +
                        "</div>")($scope);
                $("#" + divId).html(html);
            });

}

I am manipulating DOM by dynamically adding a textarea and 2 buttons.

My question is whether this approach of dynamically manipulating DOM elements is preferable in Angular world. Or should I go for some other approach (like using ng-show/ng-hide directives to show/hide the textarea and 2 buttons).

Note: I preferred not to use ng-show/ng-hide since I didn't want to introduce an extra textarea and 2 buttons for every post.

Please guide me regarding this.

1 Answer 1

1

I think you should use Directives.

putting your HTML inside the javascript is bad, and breaks the idea behind angular which aims to separate the logic from the view, and keep your objects lossly-coupled.

see similar question here: HTML template in AngularJS like KnockoutJS

Sign up to request clarification or add additional context in comments.

3 Comments

So adding a textarea(using ng-show/ng-hide) for each post on the page is fine? For 100's of posts, it would mean adding that many textareas and buttons.
No, you would build one template that will be used for all your items.
Yes. But still all textareas would be loaded at compile time right? with the binded model values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.