更新:在代码的另一部分中,它一定是愚蠢的。它现在有效,所以bindToController语法很好。
我们正在使用AngularJS 1.4,它在指令中引入了new way to use bindToController。
经过相当多的阅读(也许并不了解所有内容),我们定义了这样的指令:
.directive('mdAddress', function mdAddress() {
var directive = {
restrict: 'EA',
scope: {},
bindToController: {
address: '='
},
templateUrl: 'modules/address/address.html',
controller: AddressController,
controllerAs: 'dir'
};
从另一个视图中调用它:
<md-address address="vm.address"></md-address>
之前已在视图控制器中定义:
vm.address = {
street: null,
countryCode: null,
cityCode: null,
postalCode: null
};
引用指令模板中的变量,如下所示:
<md-input-container>
<label>{{'ADDRESSNUMBER' | translate}}</label>
<input type="number" ng-model="dir.address.streetNumber">
</md-input-container>
我们花了4小时试图弄清楚为什么我们的指令不起作用。好吧,它正在工作,但控制器和指令之间的双向绑定不是,vm.address.street
无可救药地设置为null。
过了一会儿,我们只是尝试了旧方式:
.directive('mdAddress', function mdAddress() {
var directive = {
restrict: 'EA',
scope: {
address: '='
},
bindToController: true,
templateUrl: 'modules/address/address.html',
controller: AddressController,
controllerAs: 'dir'
};
它神奇地起作用了。任何想法为什么?
答案 0 :(得分:19)
<强>更新强>
感谢reference to this blog post,我需要更新我的回答。从AngularJS 1.4看来,你可以使用
scope: {},
bindToController: {
variable: '='
}
将执行与旧语法(确切)相同的操作:
scope: {
variable: '='
},
bindToController: true
来自AngularJS源代码的有用行来解释这种行为:
if (isObject(directive.scope)) {
if (directive.bindToController === true) {
bindings.bindToController = parseIsolateBindings(directive.scope,
directiveName, true);
bindings.isolateScope = {};
} else {
bindings.isolateScope = parseIsolateBindings(directive.scope,
directiveName, false);
}
}
if (isObject(directive.bindToController)) {
bindings.bindToController =
parseIsolateBindings(directive.bindToController, directiveName, true);
}
原始回答:
希望我能解释一下为什么你所经历的这种行为是正确的,并且你确实错误地理解了范围绑定的概念。
让我解释一下,您在第一个代码段中所做的是什么:
.directive('mdAddress', function mdAddress() {
var directive = {
restrict: 'EA',
scope: {},
bindToController: {
address: '='
},
templateUrl: 'modules/address/address.html',
controller: AddressController,
controllerAs: 'dir'
};
使用scope: {}
,您为mdAddress
指令创建了一个独立的范围(没有任何继承)。这意味着:父控制器和指令之间没有数据传递。
考虑到这一点,关于您的第二个代码段:
<md-address address="vm.address"></md-address>
来自父控制器/视图的 vm.address
将被指定为指令的地址属性的表达式,但是在您之前定义隔离范围时,数据不会传递到AddressController
,因此不会可在bindToController
值中找到。
让我们将scope
对象定义视为“将传入哪些数据”,将bindToController
视为“我的视图中的控制器作为对象可以使用哪些数据”。
所以,现在让我们看看最后一个(和工作代码片段):
.directive('mdAddress', function mdAddress() {
var directive = {
restrict: 'EA',
scope: {
address: '='
},
bindToController: true,
templateUrl: 'modules/address/address.html',
controller: AddressController,
controllerAs: 'dir'
};
你也创建了一个独立的范围,但这次你添加了address
属性作为表达式传入。所以现在从第二个代码段中的视图传入的address
将在控制器的范围内可用。现在设置bindToController: true
,将所有当前作用域的属性绑定到控制器(或者更可能是controllerAs对象)。现在,它可以按预期工作,因为数据将传递到范围,数据将传递到控制器的模板范围。
这个简短的概述是否有助于您更好地理解scope
和bindToController
定义对象的概念?