【问题标题】:angularjs optimize ng-repeat with many ng-if ng-show inside itangularjs 优化 ng-repeat,其中包含许多 ng-if ng-show
【发布时间】:2016-10-01 08:14:32
【问题描述】:

我使用 AngularJS 创建一个页面,用户可以在其中更正文本(例如语法、错字...)。

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

以下代码可以工作,但页面冻结需要几秒钟才能呈现,特别是在 IE 上像 30 秒),要更正的文本可能很长,就像示例中一样。

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

有没有办法对此进行优化或以 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) ;


 }]);

【问题讨论】:

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


    【解决方案1】:

    尝试在您的&lt;span&gt; 标签中使用ng-if 而不是ng-show。这样,浏览器就不需要渲染您在编辑单词时使用的所有 DOM 节点。使用ng-show,节点会被渲染,然后使用 CSS 从 DOM 中隐藏。这意味着浏览器必须渲染您可能不使用的节点,您很可能只需要更改几个单词而不是整个文档!试试看这是否可以缩短渲染时间。

    【讨论】:

    • 感谢您的建议,我将所有 ng-show 更改为 ng-if 并使其更快,但仍然在 IE 上完全冻结:( .
    【解决方案2】:

    无论前端框架是什么,跟踪文本的每个单词都会让浏览器崩溃,无论您使用的是 V8、Turbo、4x4 还是其他什么。 只需想象节点的数量。深入了解您的 DOM 元素,在您的案例中只是您的 ng-if 跨度之一,并想象其无穷无尽的属性列表中的每一个都被跟踪。但你可能已经知道了。

    使用 angular 1.x,您可以使用简单的指令检查 textarea 是否在 mouseup 和/或 blur 和/或 mousemove 上是 $dirty

    只要连接一个服务,只要上述事件之一触发,就可以存储对整个文本区域所做的任何更改。

    简而言之,在每个事件上存储整个 textarea 会更便宜(毕竟,它的内容只是一个字符串,对于浏览器来说没有什么难处理的,即使字符串很大 - 但我我确定您关心您的用户,并且您的文本区域最终不会变得庞大)。

    要存储对 textarea 所做的所有更改,您可以使用 localStorage 和/或远程 DB,可能使用 angular locker 进行 localStorage 抽象,以及 Firebase (AngularFire),它将自动处理对给定 textarea 所做的任何更改您之前将 textarea 内容连接到 Firebase 对象。

    但您的后端当然可以是任何数据 API。我建议将有限数量的“Ctrl/Cmd+Z”存储到 localStorage 中,对于外部数据库,存储无限版本由您决定。这就是 Firebase 可以派上用场的地方,因为通过强制您遵守 JSON,您可以按月、周、日进行存储,从而加速您的检索查询,以了解最终用户何时想要返回历史记录。

    【讨论】:

    • 感谢您的帮助。这是可行的,但我想让每个修改过的单词都有一个视觉标志,就像我的 plunkr 中一样
    • 您可以通过解析 textarea 内容来做到这一点。我向您保证,如果您希望您的应用程序更快,那么您正在以错误的方式解决问题。
    • 是的,我同意你的看法。我从 textarea 开始,但我别无选择,我的厨师要求在已编辑的单词上显示视觉帮助或其他内容,而 textarea 我不能(或者我不知道如何)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多