[英]Angularjs directive to Insert text at textarea caret
我有控制器MyCtrl
和指令myText
。 當MyCtrl
的模型發生變化時,我想通過在當前位置/插入符號處插入文本來更新myText
指令的textarea
。
我試圖重用這個插入文本的代碼, 其中游標使用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="angular.js@1.2.x"></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對象?
簡短的anwser:
element[0]
會給你實際的DOM元素。
答案很長:
angular.element
總是提供一個jqLite
選擇器,它jqLite
jQuery選擇給出的結果集。 它是一組HTML元素。
使用以下參數調用方法的link
函數: scope
, element
, attrs
和ctrl
。
element
作為指令附加到的一個DOM元素的集合給出。 所以第一項是實際的HTML元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.