2014-05-01 63 views
0

我想點擊一個按鈕後,添加一些文字上一個光標位置。AngularJS的NG-模型ICM textarea的

在控制器:

$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">&nbsp;</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> 

我想要實現:用戶鍵入的文本區域=>$scope.chatMsg一些文字得到的值textarea。現在,用戶按下其中一個按鈕=>按鈕的名稱將添加到最新的光標位置。 (這是沒有問題找到最新的光標位置)

問題

還有就是$scope.chatMsg{{ chatMsg }}的DIV中的價值,並在textarea的文本之間的差異。 textarea和div的內容始終保持不變。不過,按下按鈕的名稱添加到$scope.chatMsg但textarea的內容沒有改變...

我怎樣才能解決這個問題是什麼時候? TIA

+0

你可以放在一起的jsfiddle或plunker? – SoluableNonagon

+0

http://plnkr.co/edit/lN7FulBZullRV0TG5y7T?p=preview即使沒有ng-change,它也可以很好地工作。我想我必須剝離下來我的代碼.... – LEDfan

+0

你的按鈕包含在其中一個div,並:) jQuery的需要使用getSelection插件並不總是開槍點擊 – SoluableNonagon

回答

0

我解決了所有問題。上面的plunkr表單起作用。因此,在調查了所有使用Angular Chrome擴展的作用域後,我看到chatMsg在另一個作用域中定義。因此不在我嘗試訪問的範圍內。 通過這個問題angularJS ng-model input type number to rootScope not updating我找到了一個解決方案。 我將chatMsg添加到字段對象。

0

首先,您將jQuery與AngularJS混合在一起,它看起來並不像您需要jQuery那麼多。
此外,您的聊天消息更新了3個不同的功能,因此您需要進行一些調試以查看哪些被觸發。

一般:
解決您的問題,請嘗試一些調試,做一個

$scope.$watch($scope.chatMsg, function(){ 
    console.log($scope.chatMsg); 
}); 

這將觀看所有更改chatMsg。將console.log()添加到您的每個函數中,並且您可以觀察哪個被觸發。

此外,而不是使用{{}}您的DIV中只使用NG綁定,因爲該文本是在你的DIV的唯一項目,它是清潔的,如果你的應用程序崩潰的地方。

// change from 
<div>{{ chatMsg }}</div> 
// to 
<div ng-bind="chatMsg "></div> 

更新:看到你plunker後,我修改了它,並用此來了:http://plnkr.co/edit/oNKGxRrcweiJafKCm9A5?p=preview

你的NG-重複,從而讓重複的顯示,而不是崩潰到了$指數跟蹤當有人創造了同樣的信息

+0

嗯謝謝。我會用你的提示 – LEDfan