J
J
jack3d2015-10-14 15:26:35
JavaScript
jack3d, 2015-10-14 15:26:35

Why is using $parse deprecated in angularjs?

Friends, there is such a directive (brazenly taken from github):

(function() {
  "use strict";

  angular.module('app.common').directive('match', passwordVerify);

  function passwordVerify ($parse) {
    return {
      require: '?ngModel',
      restrict: 'A',
      link: function(scope, elem, attrs, ctrl) {


        var matchGetter = $parse(attrs.match);
        var caselessGetter = $parse(attrs.matchCaseless);
        var noMatchGetter = $parse(attrs.notMatch);

        scope.$watch(getMatchValue, function(){
          ctrl.$$parseAndValidate();
        });

        ctrl.$validators.match = function(){
          var match = getMatchValue();
          var notMatch = noMatchGetter(scope);
          var value;

          if(caselessGetter(scope)){
            value = angular.lowercase(ctrl.$viewValue) === angular.lowercase(match);
          }else{
            value = ctrl.$viewValue === match;
          }
          value ^= notMatch;
          return !!value;
        };

        function getMatchValue(){
          var match = matchGetter(scope);
          if(angular.isObject(match) && match.hasOwnProperty('$viewValue')){
            match = match.$viewValue;
          }
          return match;
        }
      }
    };
  }

})();

But I was turned into a pull request with the justification that $parse == eval. But 99% of directives use parse when it is necessary to compare 2 fields.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey, 2015-10-14
Protko @Fesor

Using $parse inside a link directive is normal practice, but you need to understand why you're doing it.
In your example, it is enough to replace parse with property binding in the scope. The only reason $parse is used here is a micro-optimization to reduce the number of watchers.
updated
Correction, the only reason why $parse is used here instead of an isolated scope is that ngModel already has an isolated scope and Angular will simply not allow two directives with isolated scopes to be created on the same element.

L
lega, 2015-10-14
@lega

$parse != eval, a more or less isolated function is formed there, and eval is not terrible if you only run your own code.
"Half" Angular.js is based on $parse

B
bromzh, 2015-10-14
@bromzh

Maybe because it is almost the same as eval? Therefore, you need to carefully check the input parameters. And you immediately call it from attribute values, without even checking them for anything. Well, tracking down errors in such things is extremely difficult.
habrahabr.ru/post/244001/#comments

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question