使用ng-model的AngularJS自定义表单组件/指令

cle*_*ath 3 angularjs angularjs-directive angular-forms

角度自定义表单组件/指令和$ dirty属性

使用常规输入时,例如

<form name="myForm">
  <input type="text" ng-model="foobar">
</form>
Run Code Online (Sandbox Code Playgroud)

在输入框中键入后myForm.$dirty为true。

我想创建一个简单的指令,例如

angular.module('myModule', [])
.directive('myDirective', function() {
  return {
    restrict: 'E',
    scope: {
      fooBar: '='
    },
    template: '<div><button ng-click="fooBar=foo"></button><button ng-click="fooBar=bar"></button></div>'
  };
});
Run Code Online (Sandbox Code Playgroud)

样本用法为

<form name="myForm">
  <my-directive foo-bar="myObj.foobarValue"></my-directive>
</form>
Run Code Online (Sandbox Code Playgroud)

在用户单击两个按钮中的任何一个之后,myForm$dirty设置为true。

这是如何完成的?

geo*_*awg 5

实施自定义表单控件(使用ngModel

DDO中使用ngModel控制器require属性的对象形式:

angular.module('myModule', [])
.directive('myDirective', function() {
  return {
    restrict: 'E',
    require: { ngModelCtrl: 'ngModel' },
    scope: {
      ngModel: '<'
    },
    bindToController: true,
    controllerAs: '$ctrl',
    template: 
       `<div>
          <button ng-click="$ctrl.ngModelCtrl.$setViewValue('foo')">
              Set foo
          </button>
          <button ng-click="$ctrl.ngModelCtrl.$setViewValue('bar')">
              Set bar
          </button>
       </div>`,
    controller: function ctrl() {}
  };
});
Run Code Online (Sandbox Code Playgroud)

用法:

<form name="myForm">
    <input type="text" ng-model="foobar">
    <my-directive ng-model="foobar"></my-directive>
</form>
Run Code Online (Sandbox Code Playgroud)

通过实例化和使用ng-model控制器,该指令将根据需要自动设置表单控件。

演示

angular.module('myModule', [])
.directive('myDirective', function() {
  return {
    restrict: 'E',
    require: { ngModelCtrl: 'ngModel' },
    scope: {
      ngModel: '<'
    },
    bindToController: true,
    controllerAs: '$ctrl',
    template: 
       `<div>
          <button ng-click="$ctrl.ngModelCtrl.$setViewValue('foo')">
              Set foo
          </button>
          <button ng-click="$ctrl.ngModelCtrl.$setViewValue('bar')">
              Set bar
          </button>
       </div>`,
    controller: function ctrl() {}
  };
});
Run Code Online (Sandbox Code Playgroud)
<form name="myForm">
    <input type="text" ng-model="foobar">
    <my-directive ng-model="foobar"></my-directive>
</form>
Run Code Online (Sandbox Code Playgroud)

我建议隔离范围ngModel作为输入。输出应使用$ setViewValue方法完成

有关更多信息,请参见