angularjs优化ng-repeat,其中包含许多ng-if ng-show

时间:2016-10-01 08:14:33

标签: angularjs angularjs-ng-repeat ng-repeat angular-ng-if

我使用AngularJS创建一个用户可以更正文本的页面(例如语法,拼写错误......)。

我无法使用Textarea,因为我想跟踪更改并让用户回滚每个单词的更正。

下面的代码可以工作,但是在页面冻结时需要几秒钟的时间,特别是在IE上,如30秒),要修正的文本可以像示例中那样很长。

我使用ng-repeat来显示文本(这是一个单词数组)。对于每个单词,如果是标点符号或<br>或可编辑的单词,我会在html中发送文字。

有没有办法优化这个或以JS方式创建(比如编译html或更快的东西)?

PLUNKER

HTML

 <div ng-controller="Ctrl1">
     Correct the text 
     <span ng-repeat="word in words track by $index">
         <br ng-if="word.br"/>
         <span ng-show="(!word.br)&& !word.edited">
             <span ng-if="word.editable" class="correct-span" ng-click="word.edited = true">{{word.u}}</span>
             <span ng-if="!word.editable">{{word.u}}</span>
         </span>
         <span class="my-danger" ng-show="(!word.br)&& word.edited">
             <input type="text" ng-model="word.u">
             <button ng-click="word.edited = false;word.u = word.o">X</button>
          </span>

     </span>
 </div>

我的控制器:

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

 myApp.controller('Ctrl1', ['$scope',  function($scope) {
     function tools_isString(myVar){
        return (typeof myVar == 'string' || myVar instanceof String);
     }

     /***
      * test if object if defined
      * @param object
      * @returns {boolean}
      */
     function tools_defined(object){
        return (( typeof object !== undefined) && ( typeof object !== 'undefined') && ( object !== null ) && (object !== "")) ;
     }
     /**
      * test if a word is in array
      * @param mot : string
      * @param tableau : array list
      * @returns {boolean}
      */
     function tools_inArray(word, array) {
        if(tools_defined(array)&&tools_defined(word)) {
           var length = array.length;
           if (tools_isString(word)) {
              word = word.toLowerCase();
           }

           for (var i = 0; i < length; i++) {
              if (tools_isString(array[i])) {
                 array[i] = (array[i]).toLowerCase();
              }
              if (array[i] == word) return true;
           }

        }
        return false;
     }

     function escapeRegExp(string) {
        return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
     }
     function tools_replaceAll(str, find, replace) {
        if(str == null ){
           return null
        }
        return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
     }
     var prepareTextToCorrect = function(inputstring){
          //encode new lines
          inputstring = tools_replaceAll(inputstring,"<br/>","*br*");
          inputstring = tools_replaceAll(inputstring,"<br>","*br*");
          // unescape
          inputstring = inputstring.replace(/&(lt|gt);/g, function (strMatch, p1){
             return (p1 == "lt")? "<" : ">";
          });
          // remove all the hmtl tags
          var rex = /(<([^>]+)>)|(&lt;([^>]+)&gt;)/ig;
          inputstring = inputstring.replace(rex , "");
          // re encode new lines
          inputstring = tools_replaceAll(inputstring,"*br*"," <br/> ");
          // separating punctuation from words
          var ponctuations = [",","?",",",";",".",":","!","-","_","(",")","«","»","—"];
          for(var p in ponctuations){
             inputstring = tools_replaceAll(inputstring,ponctuations[p]," "+ponctuations[p]);
          }
          inputstring = tools_replaceAll(inputstring,"  "," ");
          inputstring = tools_replaceAll(inputstring,"  "," ");

          var elements = inputstring.split(" ");
          var res = [];

         /**
          * "o" : original word
          * "u" : word edited by user
          * "edited" : if user edited this word
          * "editable" : if the word can be edited ( ponctuation and <br> cannot ) 
          */
          for(var i in elements){
             if(elements[i].length>0) {
                if(elements[i] == "<br/>") {
                   res.push({
                      "o": null, "u": null, "edited": false, "br":true
                   });
                } else if (tools_inArray(elements[i], ponctuations)) {
                   res.push({
                      "o": elements[i], "u": elements[i], "edited": false,"editable": false , "br":false
                   });
                }else{
                   res.push({
                      "o": elements[i], "u": elements[i], "edited": false,"editable": true , "br":false
                   });
                }
             }
          }
          return res ;
       };


    var text = "Stack Overflow is a question and answer site for professional and enthusiast programmers. It's built and run by you as part of the Stack Exchange network of Q&A sites. With your help, we're working together to build a library of detailed answers to every question about programming.<br/><br/>We're a little bit different from other sites. Here's how:<br/>Ask questions, get answers, no distractions<br/><br/>This site is all about getting answers. It's not a discussion forum. There's no chit-chat.<br/><br/>Just questions...<br/>...and answers.<br/>Good answers are voted up and rise to the top.<br/><br/>The best answers show up first so that they are always easy to find.<br/>accept<br/><br/>The person who asked can mark one answer as accepted.<br/><br/>Accepting doesn't mean it's the best answer, it just means that it worked for the person who asked.<br/>Do Swift-based applications work on OS X 10.9/iOS 7 and lower?<br/>up vote 14 down vote favorite<br/><br/>Will Swift-based applications work on OS X 10.9 (Mavericks)/iOS 7 and lower?<br/><br/>For example, I have a machine running OS X 10.8 (Mountain Lion), and I am wondering if an application I write in Swift will run on it.<br/>ios osx swift<br/>asked Jun 2 '14 at 19:25<br/>MeIr<br/>3,27752557<br/>2 Answers<br/>up vote 4 down vote accept<br/><br/>Swift code can be deployed to OS X 10.9 and iOS 7.0. It will usually crash at launch on older OS versions.<br/>answered Jun 3 '14 at 8:25<br/>Greg Parker<br/>6,21011118<br/>up vote 3 down vote<br/><br/>Apple has announced that Swift apps will be backward compatible with iOS 7 and OS X Mavericks. The WWDC app is written in Swift.<br/>answered Jun 3 '14 at 0:03<br/>Ben Gottlieb<br/>73.3k19161166<br/>Get answers to practical, detailed questions<br/><br/>Focus on questions about an actual problem you have faced. Include details about what you have tried and exactly what you are trying to do.<br/><br/>Ask about...<br/><br/>Specific programming problems<br/>Software algorithms<br/>Coding techniques<br/>Software development tools<br/><br/>Not all questions work well in our format. Avoid questions that are primarily opinion-based, or that are likely to generate discussion rather than answers.<br/><br/>Questions that need improvement may be closed until someone fixes them.<br/><br/>Don't ask about...<br/><br/>Questions you haven't tried to find an answer for (show your work!)<br/>Product or service recommendations or comparisons<br/>Requests for lists of things, polls, opinions, discussions, etc.<br/>Anything not directly related to writing computer programs<br/><br/>Tags make it easy to find interesting questions<br/><br/>Stack Overflow is a question and answer site for professional and enthusiast programmers. It's built and run by you as part of the Stack Exchange network of Q&A sites. With your help, we're working together to build a library of detailed answers to every question about programming.<br/><br/>We're a little bit different from other sites. Here's how:<br/>Ask questions, get answers, no distractions<br/><br/>This site is all about getting answers. It's not a discussion forum. There's no chit-chat.<br/><br/>Just questions...<br/>...and answers.<br/>Good answers are voted up and rise to the top.<br/><br/>The best answers show up first so that they are always easy to find.<br/>accept<br/><br/>The person who asked can mark one answer as accepted.<br/><br/>Accepting doesn't mean it's the best answer, it just means that it worked for the person who asked.<br/>Do Swift-based applications work on OS X 10.9/iOS 7 and lower?<br/>up vote 14 down vote favorite<br/><br/>Will Swift-based applications work on OS X 10.9 (Mavericks)/iOS 7 and lower?<br/><br/>For example, I have a machine running OS X 10.8 (Mountain Lion), and I am wondering if an application I write in Swift will run on it.<br/>ios osx swift<br/>asked Jun 2 '14 at 19:25<br/>MeIr<br/>3,27752557<br/>2 Answers<br/>up vote 4 down vote accept<br/><br/>Swift code can be deployed to OS X 10.9 and iOS 7.0. It will usually crash at launch on older OS versions.<br/>answered Jun 3 '14 at 8:25<br/>Greg Parker<br/>6,21011118<br/>up vote 3 down vote<br/><br/>Apple has announced that Swift apps will be backward compatible with iOS 7 and OS X Mavericks. The WWDC app is written in Swift.<br/>answered Jun 3 '14 at 0:03<br/>Ben Gottlieb<br/>73.3k19161166<br/>Get answers to practical, detailed questions<br/><br/>Focus on questions about an actual problem you have faced. Include details about what you have tried and exactly what you are trying to do.<br/><br/>Ask about...<br/><br/>Specific programming problems<br/>Software algorithms<br/>Coding techniques<br/>Software development tools<br/><br/>Not all questions work well in our format. Avoid questions that are primarily opinion-based, or that are likely to generate discussion rather than answers.<br/><br/>Questions that need improvement may be closed until someone fixes them.<br/><br/>Don't ask about...<br/><br/>Questions you haven't tried to find an answer for (show your work!)<br/>Product or service recommendations or comparisons<br/>Requests for lists of things, polls, opinions, discussions, etc.<br/>Anything not directly related to writing computer programs<br/><br/>Tags make it easy to find interesting questions<br/><br/>Stack Overflow is a question and answer site for professional and enthusiast programmers. It's built and run by you as part of the Stack Exchange network of Q&A sites. With your help, we're working together to build a library of detailed answers to every question about programming.<br/><br/>We're a little bit different from other sites. Here's how:<br/>Ask questions, get answers, no distractions<br/><br/>This site is all about getting answers. It's not a discussion forum. There's no chit-chat.<br/><br/>Just questions...<br/>...and answers.<br/>Good answers are voted up and rise to the top.<br/><br/>The best answers show up first so that they are always easy to find.<br/>accept<br/><br/>The person who asked can mark one answer as accepted.<br/><br/>Accepting doesn't mean it's the best answer, it just means that it worked for the person who asked.<br/>Do Swift-based applications work on OS X 10.9/iOS 7 and lower?<br/>up vote 14 down vote favorite<br/><br/>Will Swift-based applications work on OS X 10.9 (Mavericks)/iOS 7 and lower?<br/><br/>For example, I have a machine running OS X 10.8 (Mountain Lion), and I am wondering if an application I write in Swift will run on it.<br/>ios osx swift<br/>asked Jun 2 '14 at 19:25<br/>MeIr<br/>3,27752557<br/>2 Answers<br/>up vote 4 down vote accept<br/><br/>Swift code can be deployed to OS X 10.9 and iOS 7.0. It will usually crash at launch on older OS versions.<br/>answered Jun 3 '14 at 8:25<br/>Greg Parker<br/>6,21011118<br/>up vote 3 down vote<br/><br/>Apple has announced that Swift apps will be backward compatible with iOS 7 and OS X Mavericks. The WWDC app is written in Swift.<br/>answered Jun 3 '14 at 0:03<br/>Ben Gottlieb<br/>73.3k19161166<br/>Get answers to practical, detailed questions<br/><br/>Focus on questions about an actual problem you have faced. Include details about what you have tried and exactly what you are trying to do.<br/><br/>Ask about...<br/><br/>Specific programming problems<br/>Software algorithms<br/>Coding techniques<br/>Software development tools<br/><br/>Not all questions work well in our format. Avoid questions that are primarily opinion-based, or that are likely to generate discussion rather than answers.<br/><br/>Questions that need improvement may be closed until someone fixes them.<br/><br/>Don't ask about...<br/><br/>Questions you haven't tried to find an answer for (show your work!)<br/>Product or service recommendations or comparisons<br/>Requests for lists of things, polls, opinions, discussions, etc.<br/>Anything not directly related to writing computer programs<br/><br/>Tags make it easy to find interesting questions<br/><br/>Stack Overflow is a question and answer site for professional and enthusiast programmers. It's built and run by you as part of the Stack Exchange network of Q&A sites. With your help, we're working together to build a library of detailed answers to every question about programming.<br/><br/>We're a little bit different from other sites. Here's how:<br/>Ask questions, get answers, no distractions<br/><br/>This site is all about getting answers. It's not a discussion forum. There's no chit-chat.<br/><br/>Just questions...<br/>...and answers.<br/>Good answers are voted up and rise to the top.<br/><br/>The best answers show up first so that they are always easy to find.<br/>accept<br/><br/>The person who asked can mark one answer as accepted.<br/><br/>Accepting doesn't mean it's the best answer, it just means that it worked for the person who asked.<br/>Do Swift-based applications work on OS X 10.9/iOS 7 and lower?<br/>up vote 14 down vote favorite<br/><br/>Will Swift-based applications work on OS X 10.9 (Mavericks)/iOS 7 and lower?<br/><br/>For example, I have a machine running OS X 10.8 (Mountain Lion), and I am wondering if an application I write in Swift will run on it.<br/>ios osx swift<br/>asked Jun 2 '14 at 19:25<br/>MeIr<br/>3,27752557<br/>2 Answers<br/>up vote 4 down vote accept<br/><br/>Swift code can be deployed to OS X 10.9 and iOS 7.0. It will usually crash at launch on older OS versions.<br/>answered Jun 3 '14 at 8:25<br/>Greg Parker<br/>6,21011118<br/>up vote 3 down vote<br/><br/>Apple has announced that Swift apps will be backward compatible with iOS 7 and OS X Mavericks. The WWDC app is written in Swift.<br/>answered Jun 3 '14 at 0:03<br/>Ben Gottlieb<br/>73.3k19161166<br/>Get answers to practical, detailed questions<br/><br/>Focus on questions about an actual problem you have faced. Include details about what you have tried and exactly what you are trying to do.<br/><br/>Ask about...<br/><br/>Specific programming problems<br/>Software algorithms<br/>Coding techniques<br/>Software development tools<br/><br/>Not all questions work well in our format. Avoid questions that are primarily opinion-based, or that are likely to generate discussion rather than answers.<br/><br/>Questions that need improvement may be closed until someone fixes them.<br/><br/>Don't ask about...<br/><br/>Questions you haven't tried to find an answer for (show your work!)<br/>Product or service recommendations or comparisons<br/>Requests for lists of things, polls, opinions, discussions, etc.<br/>Anything not directly related to writing computer programs<br/><br/>Tags make it easy to find interesting questions<br/><br/>" ;
    $scope.words = prepareTextToCorrect(text) ;


 }]);

2 个答案:

答案 0 :(得分:1)

尝试在ng-if标记中使用ng-show代替<span>。通过这种方式,浏览器不需要渲染编辑单词时使用的所有DOM节点。使用ng-show渲染节点,然后使用CSS从DOM中隐藏节点。这意味着浏览器必须渲染您可能不使用的节点,很可能您只需更改几个单词而不是整个文档!试着看看这是否可以改善渲染时间。

答案 1 :(得分:0)

无论前端框架是什么,跟踪文本的每个单词都会让浏览器瘫痪,无论你有V8,Turbo,4x4还是其他什么。 只是想象一下节点的数量。深入了解一下您的DOM元素,只是您的ng-if范围中的一个,并想象每个跟踪的无限属性列表。但你可能已经知道了。

使用角度1.x,您可以检查textarea和/或$dirty上的mouseupblur,还是mousemove上的/ package javaapplication13; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; public class JavaApplication13 { public static void main(String[] args) { // TODO code application logic here BufferedReader br; String strLine; ArrayList<String> arr =new ArrayList<>(); HashMap<Integer,ArrayList<String>> hm = new HashMap<>(); try { br = new BufferedReader( new FileReader("words.txt")); while( (strLine = br.readLine()) != null){ arr.add(strLine); } } catch (FileNotFoundException e) { System.err.println("Unable to find the file: fileName"); } catch (IOException e) { System.err.println("Unable to read the file: fileName"); } ArrayList<Integer> lengths = new ArrayList<>(); //List to keep lengths information System.out.println("Total Words: "+arr.size()); //Total waords read from file int i=0; while(i<arr.size()) //this loop will itrate our all the words of text file that are now stored in words.txt { boolean already=false; String s = arr.get(i); //following for loop will check if that length is already in lengths list. for(int x=0;x<lengths.size();x++) { if(s.length()==lengths.get(x)) already=true; } //already = true means file is that we have an arrayist of the current string length in our map if(already==true) { hm.get(s.length()).add(s); //adding that string according to its length in hm(hashmap) } else { hm.put(s.length(),new ArrayList<>()); //create a new element in hm and the adding the new length string hm.get(s.length()).add(s); lengths.add(s.length()); } i++; } //Now Print the whole map for(int q=0;q<hm.size();q++) { System.out.println(hm.get(q)); } } } 一个简单的指令。

只要上述某个事件触发,只需连接存储对整个textarea所做更改的服务。

简而言之,将整个textarea存储在每个事件上会更便宜(毕竟,它的内容只是一个字符串,对于浏览器来说,即使字符串很大也没什么难的。 - 但我确定你关心你的用户,而你的textarea最终还是不会成功。

要存储对textarea所做的每个更改,您可以使用localStorage和/或远程数据库,可能使用angular locker进行localStorage抽象,使用Firebase (AngularFire),它将自动处理所做的任何更改鉴于您之前已将textarea内容连接到Firebase对象,请到textarea。

但是你的后端当然可以是任何数据API。我建议存储有限数量的&#34; Ctrl / Cmd + Z&#34;进入localStorage,对于外部数据库,嗯,它可以存储无限版本。这就是Firebase会派上用场的原因,因为通过强制您遵守JSON,您可以按月,周,日进行存储,从而加快您的检索查询,以便最终用户想要回到历史记录中。