【发布时间】:2018-01-06 03:54:35
【问题描述】:
我有一个问题,关于我们如何在没有 $scope 或 $rootScope 但类似于 Angular (2/4) 的情况下将数据从一个组件传递到另一个组件。假设我有三个组件:
- rootComponent:应用程序的入口点
- phoneListComponent:显示手机列表
- phoneDetailComponent:显示所选手机的详细信息
root组件源码:
'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模块中。
由于组件有自己的隔离作用域,我无法将所选属性从 phoneList 传递给 phoneDetail。知道我寻求松散耦合并且没有 $scope 或 $rootScope 的情况下,有哪些可能的解决方案?
我已经在 StackOverflow 上看到了这个答案 here,但在我看来,如果没有在它们之上编排的父模块,我的模块将无法工作,但情况并非总是如此。
谢谢
【问题讨论】:
-
您可能想要定义一个服务并将其注入到两个组件中。这样您就可以定义与
phones数组管理相关的常用方法。或者,您可以注入$rootScope并将phones存储为$rootScope.phones。
标签: javascript angularjs angularjs-directive components angularjs-components