Search code examples
javascriptangularjsangularjs-directiveangular-ngmodel

Angular: Get ng-model by ng-attr-id?


Is there a way to get ng-model value by ng-attr-id ?

I'm making a Comment/Reply box and I would like to get the value of the current reply.

Here is my html--

<div class="comments-list" ng-show="CommentsLoaded">
    <ul>
        <li ng-repeat="comment in comments">
            <div>
                {{comment.content}}
            </div>
            <div ng-click="showReply(comment.id)">
                Reply
            </div>
            <div ng-class="hideReply" ng-attr-id="{{'reply-'+comment.id}}">
                <textarea ng-model="replytxt" ng-attr-id="{{'replytxt-'comment.id}}"></textarea>
                <div class="form-group">
                    <button type="button" ng-click="sendReply(comment.id)">
                        Publier
                    </button>
                </div>
            </div>
        </li>
    </ul>
</div>

Here is the angularjs--

$scope.sendReply = function(commentId){
    var elm = document.getElementById('replytxt-'+commentId);
    console.log(elm);
}

The above function show this in console:

<textarea ng-model="replytxt"  ng-attr-id="{{'replytxt-'+comment.id}}" class="ng-pristine ng-valid ng-touched" id="replytxt-31"></textarea>

Solution

  • You don't need to retrieve element value by its selector. Do pass replytxt value inside sendReply function itself on click.

    ng-click="sendReply(comment.id, replytxt)"
    
    $scope.sendReply = function(commentId, replytxt){
    

    Suggestion: rather than having replytxt there independently as ng-model, you can put it on comment level property like comment.replytxt, so that you don't need to take care of passing replytxt value separately to server.

    ng-click="sendReply(comment)"
    

    Code

    $scope.sendReply = function(comment){
        console.log(comment.id, comment.replytxt);
    }