0

I have this code:

            <label>
                Text {{ ers.verify(cos.contentForm.contentText, 5) }}
            </label>
            <textarea id="contentText"
                      name="contentText"
                      ng-minlength="5"
                      ng-model="cos.content.text"
                      ng-required="true"></textarea>

and a verify function:

verify = function (field, min, pattern) {    
    if (pattern == undefined) {
        pattern = false;
    }
    if (angular.isDefined(field)) {
        if (field.$error.required) return "*";
        if (min) {
            if (field.$error.minlength) {
                var msg = "> " + min + " char"
                return msg;
            }
        }
    }
    return "";
}

Everything works and an appropriate message is given but one of my team is saying that it is wasting resources if I continuously check the value of the field.

Is there a better way to do this that would be more efficient. For example I was thinking to have the ng-change event call a function.

  • It sounds like you've already answered your own question and you've got a team member who can back you up on that. – GolezTrol Dec 19 '15 at 08:10
  • So are you saying it is a waste of resources? How significant a waste is it as I thought one of the key things about AngularJS was that what shows up on the screen is continuously checked anyway. –  Dec 19 '15 at 08:14

1 Answers1

0

Although you might not notice on modern computers, it can be considered a waste as {{ expressions }} will be evaluated at each digest cycle. This is explained very well here.

One alternative is to use Text {{text}} and use a watch on your contentText (this is simplified, as your contextText is not a property directly in scope):

   $scope.$watch('contentText', function() {
       // do your stuff here
   });

{{text}} is evaluated at each digest cycle, but your function logic will execute only when your input changes. This is particularly useful when function computation is expensive (CPU, time etc.)

Community
  • 1
  • 1
Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164