我正在尝试在点击按钮后向最后一个光标位置添加一些文字。
在控制器中:
$scope.addEmoji = function(name){
var element = $("#chat-msg-input-field");
element.focus(); //ie
var selection = element.getSelection();
var textBefore = $scope.chatMsg.substr(0, selection.start);
var textAfter = $scope.chatMsg.substr(selection.end);
$scope.chatMsg = textBefore + name + textAfter;
}
$scope.updateChatMsg = function(chatMsg){
$scope.chatMsg = chatMsg;
}
$scope.sendChatMsg = function(){
var backend = $scope.convs[$scope.active.conv].backend.name;
$scope.view.addChatMsg($scope.active.conv, $scope.active.user, $scope.chatMsg,new Date().getTime() / 1000, backend);
Chat[backend].on.sendChatMsg($scope.active.conv, $scope.chatMsg);
$scope.chatMsg = '';
};
然后是一些HTML:
<div class="chat-msg-button" >
<button ng-click="view.toggle('emojiContainer')" ><img src="/apps/chat/img/emoji/smile.png"></button>
</div>
<form id="chat-msg-form" ng-submit="sendChatMsg()">
<div class="chat-msg-button" >
<button type="submit"><div class="icon-play"> </div></button>
</div>
<div id="chat-msg-input">
<textarea id="chat-msg-input-field" autocomplete="off" type="text" ng-model="chatMsg" ng-change="updateChatMsg(chatMsg)" placeholder="Chat message"></textarea>
<div>{{ chatMsg }}</div>
</div>
</form>
我想要实现的目标:用户在textarea =&gt;中键入一些文本$scope.chatMsg
获取textarea的值。现在用户按下按钮之一=&gt;按钮的名称将添加到最新的光标位置。 (找到最新的光标位置没问题)
问题
div中$scope.chatMsg
,{{ chatMsg }}
的值与textarea中的文本之间存在差异。
textarea和div的内容始终保持不变。但是当按下按钮时,名称会添加到$scope.chatMsg
,但textarea的内容不会更改......
我该如何解决这个问题? TIA
答案 0 :(得分:0)
首先,你将jQuery与AngularJS混合在一起,看起来你不需要jQuery这么多。
此外,您的聊天消息在3个不同的功能中更新,因此您需要进行一些调试以查看触发的内容。
一般来说:
要解决您的问题,请尝试更多调试,执行
$scope.$watch($scope.chatMsg, function(){
console.log($scope.chatMsg);
});
这将监视chatMsg的所有更改。将console.log()添加到每个函数中,您可以查看触发的内容。
另外,不要在div中使用{{}},只需使用ng-bind,因为该文本是div中唯一的项目,如果你的应用程序在某个地方崩溃,它会更清晰。
// change from
<div>{{ chatMsg }}</div>
// to
<div ng-bind="chatMsg "></div>
更新:看到你的傻瓜之后,我修改了它并提出了这个:http://plnkr.co/edit/oNKGxRrcweiJafKCm9A5?p=preview
您的ng-repeat需要由$ index跟踪,以便在有人创建相同的消息时显示重复项而不是崩溃
答案 1 :(得分:0)
我解决了所有问题。上面的plunkr形式起作用。因此,在使用Angular chrome扩展调查所有范围后,我看到chatMsg在另一个范围内定义。因此,不在我试图访问它的范围内。 通过这个问题angularJS ng-model input type number to rootScope not updating我找到了一个解决方案。 我将chatMsg添加到了fields对象。