在ng-click中传递元素

Passing element in ng-click

本文关键字:元素 ng-click      更新时间:2023-09-26

我需要在ng-click中传递一个元素作为参数。

<textarea id="chat-msg" name="chat-msg" class="p-r-40 chat-reply form-control"></textarea>
<img src="libs/converse/lib/emoji/smile.png" class="image-size" ng-click="insertEmotion(document.getElementById('chat-msg'))" ></img>

这里onclick工作得很好,但我如何在ng-click中传递它?

考虑将document.getElementById部分移动到insertEmotion()函数中。

像这样调用insertEmotion('chat-msg'),其中insertEmotion将元素名称作为其参数

听起来你可能试图在控制器中操纵DOM,这并不是真正的"Angular方式"。一个更好的方法可能是将textarea绑定到一个模型变量,并让ngClick指令更新模型变量。

例如:

<textarea ng-model="chat"></textarea>
<img src="libs/converse/lib/emoji/smile.png" class="image-size" ng-click="chat = chat + ':-)'" ></img>

下面是说明这一点的plunkr: http://plnkr.co/edit/d0hMVbrwKy6nBgVxWBQP?p=preview

也许尝试创建聊天对象并将模型分配给这样的视图?

http://jsfiddle.net/e9vJH/

var app = angular.module('emotionApp',[]);
app.controller('EmotionCtrl',function($scope) {
    $scope.chat = 'Chat message';
    $scope.insertEmotion = function(emotion) {
        $scope.chat = $scope.chat + emotion;
    };
});

<div ng-app="emotionApp" ng-controller="EmotionCtrl">
    <textarea ng-model="chat"></textarea>
    <hr>
    <button ng-click="insertEmotion(':)')">Insert</button>
</div>