【问题标题】:Passing data between components in AngularJS在 AngularJS 中的组件之间传递数据
【发布时间】:2019-01-06 22:20:59
【问题描述】:

在不使用服务的情况下,我无法在 angularJS 中链接两个兄弟组件。我看到了例子,但我不能让它们工作。这就是我所拥有的。我失败了什么?谢谢!

cluster.js

<div class="row">
    <filter-component></filter-component>
    <result-component filters="$ctrl.filters"></result-component>
</div>

filter.component.js

'use strict';
    angular
        .module('filter' , ['ui.bootstrap'])
        .component('filterComponent', {
            bindings: {},
            templateUrl : 'app/filter/filter.html',
            controller : filterCtrl
        })


        function filterCtrl($scope){
            this.filters = 'FILTRO' // <-- I give it a value
        }

results.component.js

(function(){
    'use strict';
        angular
            .module('result')
            .component('resultComponent', {
                bindings: {
                    filters :'<' // <-- inject
                },
                templateUrl : 'app/result/result.html',
                controller : resultCtrl
            })


            function resultCtrl($scope) {}

结果.html

<h1>{{$ctrl.filters}}</h1> //<-- nothing is shown :(

【问题讨论】:

  • 您在 $ctrl.filters 之外传递 &lt;filter-component&gt;&lt;/filter-component&gt; ,因此您的变量将不存在。如果只想从组件传递值,则需要创建 parentchild 类型的组件。其他使用服务或events
  • 看看stackoverflow.com/questions/50390843/…。也可以随意投票;)
  • AngularJS 团队在 V1.5 中引入了组件,以便更轻松地过渡到 Angular 2+。注入和使用 $scope 会破坏这个目的,因为 Angular 2+ 没有 $scope。

标签: angularjs data-binding binding angularjs-components


【解决方案1】:

在 HTML 中使用带有表达式绑定的属性:

<div class="row">
    <filter-component on-update="$ctrl.filters=$filters">
    </filter-component>
    <result-component filters="$ctrl.filters">
    </result-component>
</div>

&lt;filter-component&gt; 中使用&amp; 的表达式绑定:

app.component('filterComponent', {
    bindings: {onUpdate: "&"},
    templateUrl : 'app/filter/filter.html',
    controller : filterCtrl
})

function filterCtrl() {
    this.filters = 'FILTRO' // <-- I give it a value
    this.onUpdate({$filters: this.filters});
}

有关详细信息,请参阅

【讨论】:

  • 大家好,谢谢!最后我使用了 $broadcast, $on y $emit,它似乎有效,但所有答案都非常有用。
  • @Pil 将范围/rootScope 事件总线与$broadcast$emit$on 一起使用已被弃用,这将使迁移到 Angular 2+ 变得更加困难。见AngularJS 1.5+ Components do not support Watchers, what is the work around?。 AngularJS 团队在 V1.5 中引入了组件,以便更轻松地过渡到 Angular 2+。注入 $scope 及其事件总线会破坏该目的。
  • @georgewg,最后我更改了我的代码并创建了父子类型的组件,谢谢! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-26
  • 2018-02-15
  • 2020-08-08
  • 2020-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多