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
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:
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