【发布时间】:2014-02-19 11:35:22
【问题描述】:
我有控制器MyCtrl 和指令myText。当MyCtrl 中的模型发生变化时,我想通过在当前位置/插入符号插入文本来更新myText 指令的textarea。
我试图重用来自 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="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'
问题:所以我的问题是如何解决这个问题?或者如何从角度元素对象中获取real DOM 对象?
【问题讨论】:
标签: javascript jquery html angularjs dom