[英]how to use form.$addControl()
我正在使用Angular 1.0.8。 如何正确添加已编译的表单元素? 我认为它与如何使用$ addControl有关?
考虑以下示例: http : //jsfiddle.net/lesouthern/LB4Tx/
在此示例中添加选择之后,仅当输入“ myInput”时,表单才有效,它无法识别带有附加选择的“必需”指令。
<div ng-app="pageModule"
ng-controller="parentCtrl">
<script type="text/ng-template" id="myTemplate">
<select name="mySelect"
add-to-form
ng-model="val"
required
ng-options="o.id as o.name for o in options">
<option value="">Select my option...</option>
</select>
</script>
<form name="myForm"
id="myForm"
novalidate
ng-submit="mySubmit()">
<input name="myInput"
ng-model="myInput"
required />
<div id="dest"></div>
<button type="submit">Click me to submit</button>
{{myForm.$invalid}}
</form>
<button ng-click="mkSelect()">create select</button>
</div>
var pageModule = angular.module('pageModule',[])
.controller('parentCtrl',function($scope,$compile) {
$scope.options = [
{ id : "nissan", name: "Nissan" },
{ id : "toyota", name: "Toyota" },
{ id : "fiat" , name: "Fiat" },
{ id : "chevy", name: "Chevy" },
{ id : "honda", name: "Honda" },
{ id : "gmc" , name: "GMC" }
];
$scope.mkSelect = function() {
var dest = angular.element(document.getElementById('dest')),
html = angular.element(document.getElementById('myTemplate')).html().trim();
dest.append($compile(html)($scope));
}
$scope.mySubmit = function() {
console.log('this is my submit');
}
})
.directive('addToForm',function() {
return {
require : ['ngModel'],
controller : function() {},
link : function($scope,$element,$attr,$ctrls) {
var modelCtrl = $ctrls[0];
$scope.myForm.$addControl(modelCtrl);
}
}
});
form。$ addControl()是不必要的。 我更正了编译命令,现在附加的元素正在向表单控制器注册: http : //jsfiddle.net/lesouthern/8CDNc/
$scope.mkSelect = function() {
var dest = angular.element(document.getElementById('dest')),
html = angular.element(document.getElementById('myTemplate')).html().trim();
$compile(html)($scope,function(_element,_scope) {
dest.append(_element);
});
}
如果不需要$compile
html,则可以使用ng-show
指令隐藏<select>
直到需要。 注意,仍然required
JSFiddle而不使用$compile
<form>
...
<select name="mySelect" id="multipleSelect" ng-show="mkSelected"
ng-model="data.singleSelect" required>
<button type="submit">Click me to submit</button>
</form>
<button ng-click="mkSelected=true">Create Select</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.