简体   繁体   中英

How to correctly validate a non-input selector in AngularJS?

I have an angular form in the following format (simplified):

<form name="form">
    <input ng-model="$ctrl.val1" ng-required="true" />
    <my-widget data-selected-value="$ctrl.myWidgetSelectedValue" ng-required="true"></my-widget>
    <input ng-model="$ctrl.val2" ng-required="true" />
</form>

While my-widget does not contain an input per se, it is a specialized selector that updates myWidgetSelectedValue. while form.$invalid updates correctly based on the existence of other inputs, I cannot find a way to make it update also based on existence of myWidgetSelectedValue.

What is the right approach to do this?

ng-required and the other validation directives require ng-model and ngModelController to implement their standard behaviour.

You will need to update your my-widget component to use ng-model to get the benefit of using the standard directives (like ng-required ). Basically, change your data-selected-value="..." attribute to use ng-model="..." and update the controller/link function to work with the ngModelController lifecycle.

I've posted this before on other questions, but I'd recommend having a look at this video on how to use ngModel in custom components: Jason Aden - Using ngModelController to Make Sexy Custom Components as it's directly relevant to what you are trying to do.

The process of updating your myWidget component to use ng-model is implementation-specific. If you post more information about that component then we can give more guidance around what you might need to do.


Here is the code for the ngRequired directive . You can see that it doesn't actually do anything if the element it's on is missing the ng-model attribute: if (!ctrl) return;

var requiredDirective = function() {
  return {
    restrict: 'A',
    require: '?ngModel',
    link: function(scope, elm, attr, ctrl) {
      if (!ctrl) return;
      attr.required = true; // force truthy in case we are on non input element

      ctrl.$validators.required = function(modelValue, viewValue) {
        return !attr.required || !ctrl.$isEmpty(viewValue);
      };

      attr.$observe('required', function() {
        ctrl.$validate();
      });
    }
  };
};

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