我正在构建自定义表单构建指令。是的,我知道已经有很多人了,谢谢。
ngModel
在指令中使用from,我遍历了表单的控制对象的JSON数组:
$scope.myForm.controls = [{label: "foo", controlType: "input"}, {label: "bar", controlType: "checkbox"}];
从那里开始,计划是$compile
针对每个表单控件使用单独的指令。
这是主要的指令(可以正常工作):
app.directive('myDynamicForm', ['$compile', function ($compile) {
return {
restrict: 'E', // supports using directive as element only
scope: {
ngModel: "="
},
replace: true,
link: function (scope, element, attrs) {
angular.forEach(scope.ngModel, function (model) {
var el = "";
switch (model.controlType.toLowerCase()) {
case "input":
el = "<my-input ng-model='model'></my-input>";
break;
default:
break;
}
$compile(el)(scope);
element.append(el);
});
}
};
}])
用法如下:
<my-dynamic-form ng-model="myForm.controls"></my-dynamic-form>
同样,这部分工作正常。
当我创建这些基于指令的新元素时,我需要将其传递给它们(作为其ng-model),以便forEach
在主指令循环中迭代特定对象。
因此,这是一个示例控制指令:
directive('myInput', ['$compile', function ($compile) {
return {
restrict: 'E',
scope: {
ngModel: "="
},
replace: true,
templateUrl: "/templates/input.html",
link: function (scope, element) {
var obj = scope.ngModel; //<==SHOULD BE SAME AS "model" IN THE FORM BUILDING DIRECTIVE!!
}
};
}])
用法:
<myInput ng-model="[model from parent form building directive]"></myInput>
现在,如果我将子指令的ng-model设置为,则会<my-input ng-model='ngModel'></my-input>
得到与父指令相同的集合。
如果我将其设置为“样板”<my-input ng-model='model'></my-input>
我得到undefined
的子指令的值。
任何帮助表示赞赏。
尝试按索引访问子模型:
app.directive('myDynamicForm', ['$compile', function ($compile) {
return {
restrict: 'E', // supports using directive as element only
scope: {
ngModel: "="
},
replace: true,
link: function (scope, element, attrs) {
angular.forEach(scope.ngModel, function (model, index) {
var el = "";
switch (model.controlType.toLowerCase()) {
case "input":
el = "<my-input ng-model='ngModel[" + index + "]'></my-input>";
break;
default:
break;
}
$compile(el)(scope);
element.append(el);
});
}
};
}])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句