1

I have defined a directive with the function createDOMWallPost in the scope. The function appends the newWallPost to the element which has the dynamic-wall attribute, if the http request goes well (server responds "OK")

angular.module('p2l.directives', []).directive('dynamicWall', function(){
    return function(scope, element, attrs){
        scope.createDOMWallPost = function(newWallPost){
            $(element).append(newWallPost);
        }
    }
});

And in the controller I have

var newWallPost = $scope.newWallPost;
$http.post("/backend/newWallPost",
    {
        newWallPost : newWallPost
    }).success(function(data){
        if(data == "OK"){
            $scope.createDOMWallPost(newWallPost);
        }
    });

This works, but it does not feel like its the right way to accomplish this. What other techniques could be used for this?

1
  • 1
    Using ng-repeat with a array of wallposts would work. Why is directive required? Commented Sep 13, 2013 at 10:21

1 Answer 1

1

What you are doing is more the jquery way then the angular way. As Chandermani said in the comment. Skip the directive and when you post a new wallPost return json data including all posts from your API, save the returned data into a $scope variable and use ng-repeat to update the DOM with the new post.

Also, you do not need to use $scope.varName = function(){} when creating a function thats not gonna be executed in the template.

Some quick pseudocode

#Controller
var newWallPost = $scope.newWallPost;
$http.post("/backend/newWallPost",
    {
        newWallPost : newWallPost
    }).success(function(data){
        if(data == "OK"){
            $scope.wallPosts = data;
        }
    });

#Template
<p ng-repeat="post in wallPosts">{{ post.jsonKey }}</p>
Sign up to request clarification or add additional context in comments.

2 Comments

You're correct in assuming its the jQuery way! Your answer is more angular-y. Thanks
Normally when you feel that you want/need to use jQuery to acomplish something, save some time in asking a question here or join #angularjs on irc@freenode and just ask how it should be done. Almost always there is a much simpler more effective way of doing it :) gl and happy coding!

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.