实施自定义表单控件(使用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() {} };});用法:
<form name="myForm"> <input type="text" ng-model="foobar"> <my-directive ng-model="foobar"></my-directive></form>
通过实例化和使用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() {} };});<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方法完成。
有关更多信息,请参见
AngularJS开发人员指南-实现自定义表单控件(使用
ngModel
)AngularJS开发人员指南-基于组件的应用程序体系结构



