简体   繁体   中英

Custom handlebars helpers in AngularJS

I have an extensive form for a web application and I noticed that a lot of the input and validation information repeats itself. Is there any way to cut this down and register a handlebars helper method? For example, I would prefer chopping down this code a bit:

<span class="form-control-error" ng-show="personalForm.first_name.$invalid && !personalForm.first_name.$pristine || submitted && personalForm.first_name.$invalid">
   <span ng-show="personalForm.first_name.$error.required">First Name is required</span>
</span>

There's an angular directive which is ideally suited for this: ngMessages - https://docs.angularjs.org/api/ngMessages

This would be equivalent to your current code:

<span class="form-control-error" ng-show="shouldShowFormErrors(personalForm.first_name)" ng-messages="personalForm.first_name.$errors">
   <span ng-message="required">First Name is required</span>
</span>

Add a function to your controller like this:

$scope.shouldShowFormErrors = function(formElement){
    return $scope.submitted || formElement.$pristine;
};

To cut down on even more markup, you can use a template with ngMessages, but unless you can use generic error messages (the one in your example is specific to that field) that's not suitable.

If you REALLY want to cut down on your code, you could make a directive that creates the ngMessages span tags with the personalized message. Depends on how far you want to take it.

I also recommend using the $touched property rather than the $pristine property. I prefer the behaviour of it for these kinds of situations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM