AngularJS form $addControl 注册控件control

来源:互联网 发布:魔域网络客服 编辑:程序博客网 时间:2024/05/22 20:44

需求背景:

在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

1 0
原创粉丝点击