AngularJS form $addControl 注冊控件control

需求背景:

在form中使用编写的某component directive时。想通过form's name来对form中控件进行操作,
如使用$invalid等来ng-disabled btn。

解决方式

通过使用form.$addControl将控件中的control注冊到form中,既可使用form's name.xxx.$invalid方式来操作。

详细方法:

    tw.directive('nameForForm', function() {
      return {
        restrict: 'A',
        require: "?ngModel",
        link: function($scope, elem, attrs, ngModelCtrl) {
          
          var formController = elem.controller('form') || {
            $addControl: angular.noop
          };
          
          ngModelCtrl.$name = attrs.workflowNameForForm;
          formController.$addControl(ngModelCtrl);

          $scope.$on('$destroy', function() {
            formController.$removeControl(ngModelCtrl);
          });

          return true;
        }
      };
    });

使用方式:

component:

<div class="btn-group select select-block mbn">
  ...
  <input type="text" ng-show="false" ng-model="selectedValue" ng-required="selectRequired" 
      name-for-form="{{nameForForm}}" />
</div>

注意:在component中引入nameForForm,且scope中加入nameForForm: '@'

页面使用component:

<tw-select-list name-for-form="city" ... />


參考:http://www.ngnice.com/posts/81c1eb92bfbde0

原文地址:https://www.cnblogs.com/blfbuaa/p/7265639.html