使用rangy-javascript获取突出显示的起始索引和结束索引

时间:2016-08-11 15:38:47

标签: javascript jquery angularjs highlight rangy

我有一些拼写错误的单词(window.essaySpellingErrors)。我有一篇论文文本,从tinyMCE编辑器保存在数据库中。(data.data.essay)

我想在老师的div中渲染这篇文章,以便老师评估这篇文章。

但问题是我无法在渲染时正确地突出文章中拼写错误的单词。此外,我想要每个拼写错误的单词的第一次出现的起始索引和结束索引。

因此,下次每当论文加载亮点时,可以从我之前保存的起始索引和结束索引中进行。

我正在使用rangy进行高亮度制作以及一些javascript。

这里我附加了循环拼写错误单词的每个元素的代码。

此处$scope.comments表示教师在撰写文章时所做的评论,每当教师打开评估论文时都会加载。当系统中没有添加任何评论时,默认情况下会在评论框中添加拼写错误的评论。

$scope.getEssayDetails = function(){
    // Set the essay content.
    // Write ajax call to get the essay content
    $http({
      method  : 'POST',
      url     : Helpers.constants['CONTROLLER_PATH'] + 'essayAllotment/getEssay',
      data    : $.param({'eMode':eMode ,'essayScoreID':eScoreID}), //forms user object
      headers : {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'} 
     }).success(function(data) {
            if(Helpers.ajax_response( '' , data , [] )){
                     $scope.getEvaluationEssay($.parseJSON(data.result_data));
              }
     }).error(onAjaxError);
};

$scope.getEvaluationEssay=function(data, extraParams)
{
    $("#essay_detail").html("");
    $scope.comments = [];
    $scope.togglecomment = false;
    $scope.comments = [];
    $scope.essayDetails = {};
    window.essaySpellingErrors=[];

    if(data.data.essaySpellingErrors!=undefined)
        window.essaySpellingErrors=data.data.essaySpellingErrors;
    data.data.essay=data.data.essay.replace(/&nbsp+/ig,' ');

    //essayPlainText=data.data.essay.replace(/<span class=\'sp_err\'>(.*?)<\/span>/g,"$1");
    //essayPlainText=essayPlainText.replace(/<span class=\'for_err\'>(.*?)<\/span>/g,"$1");
    //essayPlainText=essayPlainText.replace(/\n/ig,' ');
    //essayPlainText=essayPlainText.replace(/\s+/ig,' ');

    essayPlainText=data.data.essay;
    $("#essay_detail").html(essayPlainText);

    if (data.data.report.selectFeedback != "") {
        var sfbck = data.data.report.selectFeedback.split('{|~|}');
        var commentStr;
        for (var i = 0; i < sfbck.length; i++) {
            var sfbi = sfbck[i].split('|*|');
            if ((sfbi).length != 3) continue;
            sfbi.push(i);
            $scope.createCommentBox(sfbi);    
            var indexArr = sfbi[0].match(/\[(.*?)\]/);
            commentStr=indexArr[1];
            indices=sfbi[1].split('~');
            startIndex=indices[0];
            endIndex=indices[1];
            //startIndex=new RegExp('\\b' + commentStr + '\\b');
            //endIndex=startIndex+commentStr.length;

            if (!el) el = document.getElementById('essay_detail');
            if (!sel) sel = rangy.getSelection();
            if (!range) range = rangy.createRange();
            range.selectCharacters(el, startIndex, endIndex);
            sel.setSingleRange(range);
            $scope.setHilights(0,'',0);
        }    
        data.data.essay=$("#essay_detail").html();
    }else if(Object.keys(window.essaySpellingErrors).length>0){
        for (var i = 0; i < window.essaySpellingErrors.length; i++) {
            var spellWord=window.essaySpellingErrors[i];

            var regex = new RegExp('\\b' + spellWord + '\\b','gi');
            startIndex = $("#essay_detail").text().search(regex);
            //endIndex=essayPlainText.indexOf(spellWord);
            var results = new Array();//this is the results you want
            while (regex.exec($("#essay_detail").text())){
              results.push(regex.lastIndex);
            } 
            endIndex=startIndex+spellWord.length;
            var title='Comment for [' + spellWord + ']';
            var label=startIndex + '~' + endIndex;
            var commentText="Misspelt : "+spellWord;
            var commentIndex=$scope.comments.length;
            var commentObj=[title,label,commentText,commentIndex];
            $scope.createCommentBox(commentObj);
            if (!el) el = document.getElementById('essay_detail');
            if (!sel) sel = rangy.getSelection();
            if (!range) range = rangy.createRange();
            range.selectCharacters(el, startIndex, endIndex);
            sel.setSingleRange(range);
            $scope.setHilights(0, '',1);    
           // }

            //$scope.togglecomment = true; 
        }    
        data.data.essay=$("#essay_detail").html();
    }

 $scope.createCommentBox = function(commentObj){
    var commentObject = { 'comment' : {'commentFor' : commentObj[0] , 'commentRange' : commentObj[1] , 'commentText' : commentObj[2], 'commentIndex' : commentObj[3]}};
    $scope.comments.push(commentObject);
};
$scope.setHilights=function(n, evalNum , isSpellErrorComment) {
//console.log('set HiliteN');
    var commentText=""; 
    rSel = rangy.getSelection(); //console.log(rSel);
    var txt = rSel.toHtml().replace(/style="background-color:#ff0000"/g, 'class="commentHilight" name="' + parseInt(startIndex) + '~' + parseInt(endIndex) + '"');
    var textK = rSel.text();
    //console.log(rSel.toHtml()+'------'+txt+'--------'+textK);
    rRange = rSel.getRangeAt(0);
    rRange.deleteContents();
    var str='<span class="commentHilight startIndex-'+ parseInt(startIndex) +' endIndex-'+parseInt(endIndex)+'" label="' + parseInt(startIndex) + '~' + parseInt(endIndex) + '">' + textK + '</span>';
    var node = rRange.createContextualFragment(str);
    rRange.insertNode(node);
    rSel.removeAllRanges();
    return;
}

0 个答案:

没有答案