【问题标题】:Angular 1.5.x - Issue with nested componentsAngular 1.5.x - 嵌套组件的问题
【发布时间】:2016-08-31 20:17:54
【问题描述】:

首先,我使用的是components。

我有这个“父母”component:

(function() {
  'use strict';

  angular
    .module('parentModule', [])
    .component('parent', {
      templateUrl: 'parent.tpl.html',
      controller: ParentCtrl,
        transclude: true,
        bindings: {
            item: '='
        }
    });

  function ParentCtrl() {
    var vm = this;
    vm.item = {
      'id': 1,
      'name': 'test'
    };
  }
})();

我只是想与另一个组件共享object item,如下所示:

(function() {
  'use strict';

  angular
    .module('childModule', [])
    .component('child', {
      templateUrl: 'child.tpl.html',
      controller: ChildCtrl,
      require: {
        parent: '^item'
      }
    });

  function ChildCtrl() {
    console.log(this.parent)
    var vm = this;

  }
})();

查看(父):

Parent Component:

<h1 ng-bind='$ctrl.item.name'></h1>
<child></child>

查看(儿童):

Child component:

Here I want to print the test that is in the parent component
<h2 ng-bind='$ctrl.item.name'></h2>

实际上我收到以下错误:

与指令一起使用的属性“项目”中的表达式“未定义” 'parent' 是不可赋值的!

这里是DEMO 以更好地说明情况

你能告诉我如何让它工作吗?

【问题讨论】:

    标签: javascript angularjs angularjs-components


    【解决方案1】:

    您需要从您的父组件中删除 bindings。 bindings 绑定到组件控制器,就像 scope 绑定到指令的范围一样。你没有向&lt;parent&gt;&lt;/parent&gt; 传递任何东西,所以你必须删除它。

    然后您的子组件requires 是父组件,而不是项目。 所以

      require: {
        parent: '^parent'
      }
    

    当然要修改子模板为:

    <h2 ng-bind='$ctrl.parent.item.name'></h2>
    

    最后,如果您想从子控制器记录父控制器中的项目,则必须编写:

      function ChildCtrl($timeout) {
        var vm = this;
        $timeout(function() {
          console.log(vm.parent.item);
        });
      }
    

    我从不需要我的组件中的超时,所以我可能错过了一些明显的东西。

    http://plnkr.co/edit/0DRlbedeXN1Z5ZL45Ysf?p=preview

    编辑:

    哦,我忘了,你需要使用 $onInit 钩子:

    this.$onInit = function() {
      console.log(vm.parent.item);
    }
    

    【讨论】:

    • 太棒了,非常感谢。所以没有必要使用transclude: true,对吧?
    【解决方案2】:

    您的孩子应该通过绑定将 item 作为输入。

    (function() {
      'use strict';
    
      angular
        .module('childModule', [])
        .component('child', {
          templateUrl: 'child.tpl.html',
          controller: ChildCtrl,
           bindings: {
            item: '='
           }
        });
    
      function ChildCtrl() {
        console.log(this.parent)
        var vm = this;
    
      }
    })();
    

    所以你的父模板看起来像

    <h1 ng-bind='$ctrl.item.name'></h1>
    <child item="$ctrl.item"></child>
    

    其余的应该都一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-18
      • 2017-01-16
      • 2018-08-27
      • 2016-07-03
      • 2016-10-03
      • 2016-10-09
      • 2017-10-23
      • 2016-07-10
      相关资源
      最近更新 更多