我有一个问题,我们如何在没有$ scope或$ rootScope的情况下将数据从一个组件传递到另一个组件,但类似于Angular(2/4)。我们假设我有三个组成部分:
rootComponent源代码:
'use strict';
angular.module('phonecatApp').
component('appRoot', {
templateUrl: 'app-root.template.html',
controller: [
function appRootController(){
var self = this;
}
]
});
phoneListComponent源代码:
'use strict';
// Register `phoneList` component, along with its associated controller and template
angular.module('phoneList').component('phoneList', {
//Note: the URL is relative to our 'index.html' file
templateUrl: 'phone-list/phone-list.template.html',
controller: [
function PhoneListController() {
var self = this;
self.phones = [
{
"name": "Huawei P9 lite",
"description": "This is one hell of a phone",
"price": "250€"
},
{
"name": "Samsung S8",
"description": "Great phone but really expensive",
"price": "700€"
}
]
self.select = function(phone){
self.selected=phone;
}
}
]
});
phoneDetailComponent源代码:
'use strict';
angular.module('phoneDetail').
component('phoneDetail', {
templateUrl: 'phone-detail/phone-detail.template.html',
bindings: {
selected: '<'
},
controller: [
function phoneDetailController(){
var self = this;
}
],
});
您可以看到每个组件都在其自己的模块中声明, phoneList模块和 phoneDetail模块在 phoneCatApp模块中注册。< / p>
由于组件有自己独立的范围,我无法将所选属性从phoneList传递给phoneDetail。有什么可能的解决方案,我知道我寻求松散耦合,没有$ scope或$ rootScope?
我已经在StackOverflow上看到了这个答案here,但在我看来,如果不是父母在他们之上编排,我的模块将无法工作,但情况并非总是如此。
谢谢
答案 0 :(得分:1)
您可以使用两种策略:
在这种情况下,我建议第一个。