【问题标题】:passing data from same level components in AngularJS从AngularJS中的同级组件传递数据
【发布时间】: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


【解决方案1】:

你可以使用两种策略:

  • 第一个是将回调传递给您的子组件(通过绑定) 您的根组件,以便您在值更改时知道 然后做你需要做的。
  • 另一种方法是使用 角度服务是一个单例,因此您可以观看特定的 值在你的控制器中,然后在它发生变化时做一些事情。

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

【讨论】:

    猜你喜欢
    • 2018-07-31
    • 2019-12-29
    • 2018-05-17
    • 2019-01-06
    • 1970-01-01
    • 2021-11-01
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多