gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:20:07 24 4
gpt4 key购买 nike

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设置为真。
这是如何实现的?

最佳答案

实现自定义表单控件(使用 ngModel)
使用 ngModel controller require property 的对象形式在 DDO 中:

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 完成.
有关更多信息,请参阅
  • AngularJS Developer Guide - Implementing custom form controls (using ngModel )
  • AngularJS Developer Guide - Component-based application architecture
  • 关于使用 ng-model 的 AngularJS 自定义表单组件/指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44875989/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com