2014-01-28 88 views
4

我有控制器MyCtrl和指令myText。當MyCtrl中的型號發生變化時,我想通過在當前位置/插入符處插入文本來更新myText指令的textareaAngularjs指令在textarea插入文本caret

我試圖從這個Inserting a text where cursor is using Javascript/jquery

我的代碼重用的代碼:http://plnkr.co/edit/WfucIVbls2eekL8kUp7e

這裏是我的HTML:

<!DOCTYPE html> 
<html ng-app="plunker"> 

    <head> 
    <meta charset="utf-8" /> 
    <title>AngularJS Plunker</title> 
    <script>document.write('<base href="' + document.location + '" />');</script> 
    <link href="style.css" rel="stylesheet" /> 
    <script data-semver="1.2.10" src="http://code.angularjs.org/1.2.10/angular.js" data-require="[email protected]"></script> 
    <script src="app.js"></script> 
    </head> 

    <body> 
    <div ng-controller="MyCtrl"> 
     <input ng-model="someInput"> 
     <button ng-click="add()">Add</button> 
     <p ng-repeat="item in items">Created {{ item }}</p> 
    </div> 

    <textarea my-text=""> 

    </textarea> 

    </body> 

</html> 

的Javascript:

var app = angular.module('plunker', []); 

app.controller('MyCtrl', function($scope, $rootScope) { 
    $scope.items = []; 

    $scope.add = function() { 
    $scope.items.push($scope.someInput); 
    $rootScope.$broadcast('add', $scope.someInput); 
    } 
}); 

app.directive('myText', ['$rootScope', function($rootScope) { 
    return { 
    link: function(scope, element, attrs) { 
     $rootScope.$on('add', function(e, val) { 
     console.log('on add'); 
     console.log(val); 

     if (document.selection) { 
      element.focus(); 
      var sel = document.selection.createRange(); 
      sel.text = val; 
      element.focus(); 
     } else if (element.selectionStart || element.selectionStart === 0) { 
      var startPos = element.selectionStart; 
      var endPos = element.selectionEnd; 
      var scrollTop = element.scrollTop; 
      element.value = element.value.substring(0, startPos) + val + element.value.substring(endPos, element.value.length); 
      element.focus(); 
      element.selectionStart = startPos + val.length; 
      element.selectionEnd = startPos + val.length; 
      element.scrollTop = scrollTop; 
     } else { 
      element.value += val; 
      element.focus(); 
     } 

     }); 
    } 
    } 
}]) 

現在不起作用,因爲element不是DOM對象。以下是錯誤:

TypeError: Object [object Object] has no method 'focus' 

問題:所以我的問題是如何解決這一問題?或者如何從角元素對象獲取真實 DOM對象?

回答

10

嘗試:

var domElement = element[0]; 

DEMO

+0

不錯。我怎麼錯過這個...... LOL –

+0

這段代碼似乎沒有更新範圍,當我嘗試調用$ apply時,我得到「$ digest已在進行中」......我應該如何更新與此相關的範圍變量文字區? – buzali

+0

@buzali:該指令被設計爲像'readonly'。使用它來更新範圍沒有意義。例如,沒有信息要更新哪個模型,它只是偵聽可能來自任何地方的「添加」事件,只是更新文本。 –

5

短anwser:

element[0] 

會給你實際的DOM元素。

龍答:

angular.element總是提供jqLite選擇,這是類同由一個jQuery選擇給出一個結果集。這是一組HTML元素。

的方法的link函數被調用具有以下PARAMS:scopeelementattrsctrl

element是作爲指令所附的一個DOM元素的集合給出的。所以第一項是實際的HTML元素。

I changed your code so that it should(?) work

+0

比接受的答案更好的答案。但是,演示代碼並未按照要求在當前位置插入文本。 – MCollard