我正在构建一个巨大的表单,调用各种指令来构建完整的表单。调用表单构建器的主页面像这样传递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
:
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
,我在访问父子控制器的双向绑定时遇到了各种问题。
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个大型表单并将它们组合在一起。因此,合并它们确实是最后的手段,因为它很难维护且难以阅读。 - 我认为除了从目前看到的情况来看,没有其他方法可以访问父指令的
ControllerAs
,从子指令的Controller
中。 - 如果我在子指令模板的ng-model中使用父级的ControllerAs,例如
<input type=“text” ng-model=“fb.formData.formFields.text" />
,那么这样做就可以正常工作,但我需要从子指令的控制器中访问相同的内容进行一些处理,但我无法做到这一点。 - 如果我摆脱
controllerAs
并再次使用$scope
,那么就像以前一样工作,但我正在尝试完全摆脱$scope
,以准备未来的Angular更改。
ControllerAs
摆脱$scope
时。请问有人能指导我在这里的选择吗?感谢您阅读我的长篇文章。
link
函数中的scope
有一个问题。从我所读到的来看,Angular 2可能会摆脱$scope
,所以由于在link()
中使用了scope
,以上代码是否会在Angular 2上失效?我知道,现在准备Angular 2可能还为时过早,但您对今天的传言有何看法? - NeelcontrollerAs
模式来接近Angular2迁移,但我这边没有解决方案。我们需要在controller
和link
函数中有作用域变量。在AngularJS问题列表中仍然存在未解决的bug:https://github.com/angular/angular.js/issues/5893 - Pankaj Parkar