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

前端 未结 2 1973
[愿得一人]
[愿得一人] 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条回答
  • 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:

    <span ng-show="(form.firstName.$dirty || submitted) && form.firstName.$error.required">First name is required!</span>
    ...
    <span ng-show="(form.lastName.$dirty || submitted) && form.lastName.$error.required">Last name is required!</span>
    ...
    <span ng-show="(form.email.$dirty || submitted) && form.email.$error.required">Email is required!</span>
    

    versus this:

    <span ng-show="isInvalid('firstName')">First name is required!</span>
    ...
    <span ng-show="isInvalid('lastName')">Last name is required!</span>
    ...
    <span ng-show="isInvalid('email')">Email is required!</span>
    
    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).
    0 讨论(0)
  • 2021-01-23 15:51

    One option is to set a $watch on the state condition. $watch can take a function parameter and so you can do this:

    $scope.$watch(function(){
        return $scope.prop1 && $scope.prop2 && $scope.prop3;        
    },function(val){
        $scope.state = val;
    });
    

    Here is a minimal demo

    0 讨论(0)
提交回复
热议问题