【问题标题】:AngularJS custom form component / directive using ng-model使用 ng-model 的 AngularJS 自定义表单组件/指令
【发布时间】:2017-12-06 03:45:52
【问题描述】:

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

使用常规输入时,如

<form name="myForm">
  <input type="text" ng-model="foobar">
</form>

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

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

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>'
  };
});

示例用法是

<form name="myForm">
  <my-directive foo-bar="myObj.foobarValue"></my-directive>
</form>

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

这是如何实现的?

【问题讨论】:

标签: angularjs angularjs-directive angular-forms


【解决方案1】:

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

在 DDO 中使用ngModel controllerrequire property 的对象形式:

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() {}
  };
});

用法:

<form name="myForm">
    <input type="text" ng-model="foobar">
    <my-directive ng-model="foobar"></my-directive>
</form>

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

The DEMO

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() {}
  };
});
<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="myModule">
    <h2>ngModel DEMO</h2>
    <form name="myForm">
        <input type="text" ng-model="foobar">
        <my-directive ng-model="foobar"></my-directive>
    </form>
    <br>myForm.$dirty = {{myForm.$dirty}}
    <br>myForm.$pristine = {{myForm.$pristine}}
    <br><button ng-click="myForm.$setDirty()">Set dirty</button>
    <br><button ng-click="myForm.$setPristine()">Set pristine</button>
  </body>

我建议使用ngModel 作为输入来隔离范围。输出应使用$setViewValue method

有关详细信息,请参阅

【讨论】:

  • 我正在构建一个指令,并希望避免代码重复。
  • 效果非常好。对我来说缺少的信息是bindToController 语法,因为所有示例都指向链接函数作为使用其他控制器的一种方式。此外,scope: { ngModel: '&lt;' } 确实派上了用场;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多