我有一个组件,例如:
Check Plunkr Example (更新并使用解决方案:)谢谢)
my-component.js 声明
(function() {
'use strict';
angular
.module('app')
.component("myComponent", {
bindings: { obj: "=" },
controller: "ComponentController",
controllerAs: "vm",
template:
'<section class="result"><h2>{{vm.title}}</2>' +
'<h3>Using the Parent Controller values</h3>' +
'<ul><li>{{ vm.obj.a }}</li><li>{{vm.obj.b}}</li></ul>' +
'<h3>Using the Children controller values:'+
'<ul class="component-controller"><li>{{ vm.copiedObj.a }}</li><li>{{vm.copiedObj.b}}</li></ul>' +
'</section>'
});
})();
我的组件 Controller
(function() {
'use strict';
angular
.module('app')
.controller('ComponentController', ComponentController);
function ComponentController() {
var vm = this;
vm.title = "I'm the Children controller"
vm.copiedObj = vm.obj; // This should store the myObj variable located in the MainController
}
})();
和一个父 Controller
(function() {
'use strict';
angular
.module('app', []);
})();
// app.controller.js
// ///////////////////
(function() {
'use strict';
angular
.module('app')
.controller('MainController', MainController);
function MainController() {
var vm = this;
vm.title = "I'm the Parent controller";
vm.myObj = {
a: "I'm the first value",
b: "I'm the second value"
};
}
})();
所以如果我有一个模板
<body ng-controller="MainController as vm">
<h2>{{vm.title}}</h2>
<my-component obj="vm.myObj"></my-component>
</body>
重要的是我有 obj="vm.myObj"对吗?
我有问题,因为甚至没有使用 vm.title :S
我不想只是将 vm.myObj 值打印到组件中,
我希望 ParentController 中的 vm.obj.value 可以访问并存储在 ComponentController 中。
最佳答案
我们使用组件的方式是使用 绑定(bind) 属性(property)。它是指令 的简化版本范围 和 绑定(bind) Controller 属性结合。
在指令中,范围 property 允许我们定义是要继承还是隔离 $scope。随着时间的推移,这种选择已被推导出为一个合理的默认值,几乎总是使我们的指令具有隔离范围。并添加了 绑定(bind) Controller 属性,我们可以定义我们想要传递到隔离范围并直接绑定(bind)到 Controller 的属性。
在组件中,使用 绑定(bind) 属性这个重复的过程被删除,因为默认情况下 $scope 总是隔离的。
一般示例:
// directive
.directive("myDirective", function myDirective() {
return {
scope: {}, // isolate scope
bindToController: {
value: "=" // two-way binding
}
};
});
// component
.component("myComponent", {
bindings: {
value: "=" // two-way binding
}
});
详细示例:
angular
.module("myApp")
.controller("MyController", function MyController() {
var vm = this;
vm.myObj = {
a: 1,
b: 2
};
})
.component("myComponent", {
bindings: { value: "=" },
controller: "MyComponentController",
controllerAs: "vm",
template: "<ul><li>vm.value.a</li><li>vm.value.b</li></ul>"
});
在您的模板中,您可以像这样传递数据:
<div ng-controller="MyController as vm">
<my-component value="vm.myObj"></my-component>
</div>
如上所述,默认情况下,数据绑定(bind)到(组件的) Controller 并可在其中访问。
请注意,我们使用的是 双向 绑定(bind)在这里。从 1.5 版开始提供的另一个特定于组件的新增功能是 < 表示 的符号单向绑定(bind)。查看“基于组件的应用架构 ” official documentation 中的部分了解更多信息。
关于AngularJS +1.5 父 Controller 如何将数据传递给组件 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37440727/