【问题标题】:Angular: Get ng-model by ng-attr-id?Angular:通过 ng-attr-id 获取 ng-model?
【发布时间】:2017-01-16 04:12:27
【问题描述】:

有没有办法通过ng-attr-id 获取ng-model 值?

我正在制作评论/回复框,我想获取当前回复的值。

这是我的 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>

这里是angularjs--

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

上面的函数在控制台中显示:

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

【问题讨论】:

    标签: javascript angularjs angularjs-directive angular-ngmodel


    【解决方案1】:

    您不需要通过其选择器检索元素值。请在点击时将replytxt 值传递给sendReply 函数本身。

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

    建议:与其把replytxt单独放在ng-model上,不如把它放在comment.replytxt这样的评论级属性上,这样就不用管传递了replytxt 值单独发送给服务器。

    ng-click="sendReply(comment)"
    

    代码

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

    【讨论】:

    • 效果很好。你的建议比我的好。非常感谢
    • @AmadouBeye 很高兴知道这一点,谢谢 ;)
    猜你喜欢
    • 2017-04-02
    • 2018-12-15
    • 2015-08-13
    • 2018-01-21
    • 2016-09-23
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    相关资源
    最近更新 更多