2017-05-09 33 views
1

我从http://fdietz.github.io/recipes-with-angular-js/common-user-interface-patterns/editing-text-in-place-using-html5-content-editable.html中提取的这个指令非常好用。AngularJS contenteditble div - 需要获取插入位置

这是我的代码。

angular 
.module('app') 
.directive("formulaEditor", function() { 
return { 
    restrict: "A", 
    require: "ngModel", 
    link: function(scope, element, attrs, ngModel) { 
     function read() { 
      ngModel.$setViewValue(element.html()); 
     } 
     ngModel.$render = function() { 
      element.html(ngModel.$viewValue || ""); 
     }; 
     element.bind("blur keyup change", function() { 
      scope.$apply(read); 
     }); 
    } 
}; 
}); 

<div formula-editor id="editor" contenteditable="true" ng-model="kpiForm.formula"></div> 

我需要让我的div上的光标位置。我不知道如何实现我发现的代码(不使用角度):Get caret position in contenteditable div including tags

有人可以帮忙吗? ty!

+0

嗨,我正在寻找类似的东西。你有没有找到解决方案? – AshD

回答

-1

var app = angular.module("myApp", []); 
 
app.directive("formulaEditor", function() { 
 
return { 
 
    restrict: "A", 
 
    require: "ngModel", 
 
    link: function(scope, element, attrs, ngModel) { 
 
     function read() { 
 
      ngModel.$setViewValue(element.html()); 
 
     } 
 
     ngModel.$render = function() { 
 
      debugger; 
 
      document.getElementById('editor').focus(); 
 
      element.html(ngModel.$viewValue || ""); 
 
     }; 
 
     element.bind("blur keyup change", function() { 
 
      scope.$apply(read); 
 
     }); 
 
    } 
 
}; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
 
<body ng-app="myApp"> 
 

 
<div formula-editor id="editor" contenteditable="true" ng-model="kpiForm.formula" style="border:2px solid black;" tabindex="-1"></div> 
 

 
</body>

嗨,我已经更新了代码集中光标在 “格”。这对你有帮助吗?

+0

我很欣赏,@praveen,但我试图找出一种方法来获得插入位置。如果光标实际上位于第5个字符上,例如... –

+0

@MarcoJr U表示window.getSelection(),其中u可以找到给出光标的插入位置的focusOffset值。 –