【发布时间】:2016-03-11 01:20:57
【问题描述】:
我正在构建一个巨大的表单,它调用各种指令来构建一个完整的表单。调用 Form Builder 的 Main Page 传递 ng-model 数据,如下所示:
<div form-builder form-data=“formData”></div>
然后Form Builder Page调用各种子指令来构建Form的各个部分:
FormBuilder.html:
<div form-fields></div>
<div photo-fields></div>
<div video-fields></div>
.. etc.. etc...
当在控制器中使用$scope 时,我在子指令中访问$scope 没有问题,如下所示:
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错误,因为 嵌套的隔离范围,所以这是不可能的。 - 如果我没有
每个表单部分的单独指令,并将它们全部包含在
formBuilder指令下的 1 个指令,然后它变成一个 宏大的指令。以上只是一个草图,但每个孩子 指令最终构建了1个大表格。所以合并它们 在一起真的是最后的手段,因为它确实变得很难 维护和不可读。 - 我认为没有办法访问
父指令的
ControllerAs来自子指令的Controller任何其他方式 从我目前所见。 - 如果我使用父级的 ControllerAs 在
子指令模板的 ng-model 像
<input type=“text” ng-model=“fb.formData.formFields.text" />,效果很好,但我 需要从 Child 指令的控制器访问相同的 一些我无法做的处理。 - 如果我摆脱
controllerAs并再次使用$scope,它像以前一样工作,但我是 试图完全摆脱$scope为自己做好准备 未来的 Angular 变化。
由于它是一种高级表单,我需要有单独的指令来处理各种表单部分,并且由于自 Angular 1.2 以来不允许嵌套的隔离范围,这使得它变得更加困难,尤其是在尝试摆脱 $scope 使用ControllerAs.
有人可以指导我在这里有哪些选择吗?感谢您阅读我的长文。
【问题讨论】:
标签: angularjs angularjs-directive angularjs-scope angular-controller angularjs-controlleras