我正在构建一个巨大的表单,它调用各种指令来构建一个完整的表单。调用 Form Builder 的 Main Page 传递 ng-model 数据,如下所示:
<div form-builder form-data=“formData”></div>
然后表单构建器页面调用各种子指令来构建表单的各个部分:
FormBuilder.html:
<div form-fields></div>
<div photo-fields></div>
<div video-fields></div>
.. etc.. etc...
在控制器中使用$scope
时,我可以毫无问题地访问$scope
in 子指令,如下所示:
function formBuilder() {
return {
restrict: 'A',
replace: true,
scope: {
formData: '='
},
templateUrl: 'FormBuilder.html',
controller: function($scope) {
$scope.formSubmit = function() {
// Submits the formData.formFields and formData.photoFields
// to the server
// The data for these objects are created through
// the child directives below
}
}
}
}
function formFields() {
return {
restrict: 'A',
replace: true,
templateUrl: 'FormFields.html',
controller: function($scope) {
console.log($scope.formData.formFields);
}
}
}
function photoFields() {
return {
restrict: 'A',
replace: true,
templateUrl: 'PhotoFields.html',
controller: function($scope) {
console.log($scope.formData.photoFields);
}
}
}
... etc..
但是自从我摆脱$scope
并开始使用以来ControllerAs
,我在访问与父子控制器的 2 路绑定时遇到了各种麻烦。
function formBuilder() {
return {
restrict: 'A',
replace: true,
scope: {
formData: '='
},
templateUrl: 'FormBuilder.html',
controller: function() {
var vm = this;
console.log(vm.formData); // Its fine here
vm.formSubmit = function() {
// I cannot change formData.formFields and formData.photoFields
// from Child Directive "Controllers"
}
},
controllerAs: ‘fb’,
bindToController: true
}
}
function formFields() {
return {
restrict: 'A',
replace: true,
templateUrl: 'FormFields.html',
controller: function() {
var vm = this;
console.log(vm.formData.formFields);
// No way to access 2 way binding with this Object!!!
}
}
}
function photoFields() {
return {
restrict: 'A',
replace: true,
templateUrl: 'PhotoFields.html',
controller: function() {
var vm = this;
console.log(vm.formData.photoFields);
// No way to access 2 way binding with this Object!!!
}
}
}
无论我尝试什么,我都会遇到障碍。我尝试过的事情是:
- 隔离范围:我尝试将
formData.formFields
和formData.photoFields
作为隔离范围传递给子指令,但是由于嵌套的隔离范围,我最终得到了$compile: MultiDir
错误,所以这是不可能的。 - 如果我没有为每个表单部分设置单独的指令,并且将它们全部放在指令下的 1 个
formBuilder
指令中,那么它就会变成一个庞大的指令。以上只是一个草图,但每个子指令最终构建了一个大表格。因此,将它们合并在一起确实是最后的手段,因为它确实变得难以维护且不可读。 - 到目前为止,我认为没有任何其他方式可以
ControllerAs
从子指令访问父指令。Controller
- 如果我在子指令模板的 ng-model like 中使用父级的 ControllerAs
<input type=“text” ng-model=“fb.formData.formFields.text" />
,那效果很好,但是我需要从子指令的控制器中访问它以进行一些我无法执行的处理。 - 如果我摆脱
controllerAs
并$scope
再次使用,它就像以前一样工作,但我试图$scope
完全摆脱它,为未来的 Angular 更改做好准备。
由于它是一种高级表单,我需要有单独的指令来处理各种表单部分,并且由于自 Angular 1.2 以来不允许嵌套隔离范围,因此它变得更加困难,尤其是在试图摆脱$scope
using ControllerAs
.
有人可以指导我在这里有什么选择吗?感谢您阅读我的长文。