有指令,my-drtv
,与 <input ng-required="true">
<div ng-form="myForm">
内.
目前内部ng-required
未绑定(bind)到其形式( myForm
),我如何设置为 my-drtv
与其父级形式相同?
(因此在初始状态 myForm.$valid
应该为 false)
JS:
var myAppModule = angular.module('myAppModule', []).
directive('myDrtv',function(){
return {
restrict: 'A',
template: '<div><input ng-required="true"></div>'
}
});
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<html ng-app="myAppModule">
<body>
<div ng-form="myForm">
<div my-drtv>
</div>
<br>
{{myForm.$valid}}
</div>
</body>
</html>
最佳答案
为了具有验证行为,输入字段必须同时具有 ngModel 和 name 属性。然后它将被注册为表单 Controller 下的控件。所以你可以这样做
.directive('myDrtv', function() {
return {
restrict: 'A',
template: '<div><input name="inp" ng-model="inp" ng-required="true"></div>'
}
});
或者更好地从外部传递模型和名称,那么指令将变得更加可重用:
.directive('myDrtv', function() {
return {
restrict: 'A',
scope: {
model: '=ngModel'
},
template: function(element, attrs) {
return '<div><input name="' + attrs.name + '" ng-model="model" ng-required="true"></div>';
}
}
});
并像这样使用它:
<div ng-form="myForm">
<div my-drtv name="some" ng-model="someField"></div>
</div>
关于javascript - 将内部指令绑定(bind)到其父表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33722491/