gpt4 book ai didi

javascript - 从 AngularJS 中的同级组件传递数据

转载 作者:行者123 更新时间:2023-12-03 03:45:42 24 4
gpt4 key购买 nike

我有一个问题,如何在没有 $scope 或 $rootScope 的情况下将数据从一个组件传递到另一个组件,但类似于 Angular (2/4)。假设我有三个组件:

  • rootComponent:应用程序的入口点
  • phoneListComponent:显示电话列表
  • phoneDetailComponent:显示所选手机的详细信息

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模块中。

由于组件有自己的隔离范围,因此我无法将选定的属性从phoneList 传递到phoneDetail。知道我寻求松散耦合并且没有 $scope 或 $rootScope 时,可能的解决方案是什么?

我已经看到这个答案 here在 StackOverflow 上,但在我看来,如果没有父级在它们之上编排,我的模块将无法工作,但情况并非总是如此。

谢谢

最佳答案

您可以使用两种策略:

  • 第一个是将回调传递给您的子组件(通过绑定(bind))您的根组件,这样您就会知道值何时发生变化,并且然后做你需要做的事情。
  • 另一种方法可能是使用 Angular 服务是一个单例,因此您可以观看特定的 Controller 中的值,然后在它发生变化时执行某些操作。

在这种情况下,我建议第一个。

关于javascript - 从 AngularJS 中的同级组件传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45401268/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com