Is it very bad to call a function that locally computes a value from an AngularJS expression?

前端 未结 2 1999
[愿得一人]
[愿得一人] 2021-01-23 15:05

I\'ve read an article on some AngularJS pitfalls using scopes, and it states that you should not use a function in expressions, and I understand that an expression may be evalua

2条回答
  •  Happy的楠姐
    2021-01-23 15:48

    No, it's not that bad.

    Not using functions in expressions would result in HTML bloated with inline javascript.

    Consider the elegance of this code:

    First name is required!
    ...
    Last name is required!
    ...
    Email is required!
    

    versus this:

    First name is required!
    ...
    Last name is required!
    ...
    Email is required!
    
    function Ctrl($scope){
      $scope.isInvalid = function(field){
        return ($scope.form[field].$dirty || $scope.submitted) && $scope.form[field].$error.required;
      };
    
      $scope.submit = function(){
        $scope.submitted = true;
        // $http.post ...
      }
    }
    

    Even Angular authors encourage using functions in expressions.

    Functions in expressions are welcome in Angular, but with these forethoughts:

    1. Functions should be "light" (in computational terms).
    2. Functions should return the same output given the same input.
    3. Functions should be self-contained (they should not affect other scope members) because otherwise they could create a $digest loop.
    4. Functions should be cacheable (if possible).

提交回复
热议问题