我有一个 AngularJS 指令,它的模板中有一个输入元素。现在我可以在标签中添加这个指令<form>
并绑定ng-model
没有任何问题。
我遇到的问题是动态添加到的输入<form>
没有显示在formContoller
其中,这使得正确的验证变得不可能。
有没有办法让一个包含在<form>
具有自己范围的指令中的指令能够动态添加将包含在formController
指令所包含的输入中的输入?
更新
因此,当我尝试构建更简单的示例时,我确实找出了问题的根本原因,这就是我$compile
用来生成所用模板的事实。我创建了 plunker 上发生的问题的简化版本:
http://plnkr.co/edit/XsyZKW?p=preview
AngularJS 代码
angular.module('directive', []).directive('containerDir', function() {
return {
scope: {
test: '@'
},
compile: function(element, attributes) {
return function(scope, element, attributes) {
scope.model = {
dataObject: {}
}
};
}
};
});
angular.module('directive').directive('inputDir', function($compile) {
return {
template: '<span></span>',
scope: {
model: '=dataModel'
},
compile: function(element, attributes) {
return {
pre: function(scope, element, attributes) {
var template = '<input type="text" name="username" ng-model="model.username" required />';
element.html($compile(template)(scope));
},
post: function(scope, element, attributes) {
}
};
}
};
});
模板
<!doctype html>
<html ng-app='directive'>
<head>
<script data-require="jquery" data-semver="2.0.1" src="http://code.jquery.com/jquery-2.0.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div container-dir>
<form name="testForm" nag-resettable-form style="padding-left: 20px;">
<div>
<label for="first-name">First Name</label>
<input id="first-name"
type="text"
name="firstName"
ng-model="model.dataObject.firstName"
required
/>
<div>value: {{model.dataObject.firstName}}</div>
<div>{{testForm.firstName.$error | json}}</div>
</div>
<div>
<label for="username">Username</label>
<span input-dir data-data-model="model.dataObject"></span>
<div>value: {{model.dataObject.username}}</div>
<div>{{testForm.username.$error | json}}</div>
</div>
<div>
{{testForm | json}}
</div>
<div style="padding-top: 1rem;">
<button class="primary" ng-click="model.submitForm()">Submit</button>
<button ng-click="resetForm(formReveal, {}, model.resetForm)">Reset</button>
</div>
</form>
</div>
</body>
</html>
这是相同的示例,没有使用 $compile 来证明没有它也可以工作:
http://plnkr.co/edit/i8Lkt1?p=preview
现在我仍然想知道我是否可以通过使用$compile
用于为指令生成 HTML 的指令动态添加输入元素来尝试做些什么。
虽然我可能能够将有问题的指令重写为 not use $compile
,但我仍然想知道这是否可能以供将来参考。