limboy
limboy

Reputation: 4089

implement embedding comments like twitter in angularjs

i know in Angular world it is better to bind data than manipulate dom elements. but i can't figure out a way to implement the 'in timeline, click a tweet, load replies, click another tweet load another replies' effects.

here is some code run into my thoughts:

<div class="tweet" ng-repeat="tweet in tweets">
    <div class="tweet-content">{{tweet}}</div>
    <a class="button" ng-click="loadreplay()">load reply</a>
    <div class="reply-container">{{reply}}</div>
</div>

if i write controller like this

app.controller('Test', function($scope){
    $scope.tweets = ["foo", "bar"];
    $scope.loadreplay = function(){
        $scope.reply = "reply";
    }
});

then all {{reply}} fields will be filled with 'reply', so in this condition, is manipulate the dom elements the only resolution? or some more "angular" way?

Upvotes: 0

Views: 210

Answers (1)

Juliane Holzt
Juliane Holzt

Reputation: 2145

Use a appropriate schema for your data/model. Considering that you would store not only the text but at least something like a ID you would use an object anyway. So think about something like this:

$scope.tweets = [
  { id:1, txt: 'foo' },
  { id:2, txt: 'bar' }
]

Then you could store the individual replies in that object as well:

$scope.loadreply = function(tweet) {
  tweet.reply = 'Reply';
}

Note: In this function you could then also use the ID to e.g. fetch the tweets from the server like this:

$scope.loadreply = function(tweet) {
  tweet.reply = LoadReplies(tweet.id);
}

You would then use the tweet specific reply attribute for display:

<div ng:repeat="tweet in tweets">
  <div>{{tweet.txt}}</div>
  <a ng:click="loadreply(tweet)">load reply</a>
  <div>{{tweet.reply}}</div>
</div>

See this fiddle for a working demo: http://jsfiddle.net/XnBrp/

Upvotes: 1

Related Questions