Angular 1.5 嵌套组件绑定父值

Angular 1.5 Nested Component Bind parent Value

本文关键字:绑定 组件 嵌套 Angular      更新时间:2023-09-26

我是 angularjs 的新手。我正在尝试角度 1.5 嵌套组件。我可以在子组件中绑定父组件属性吗?

前任:

<div ng-app='cbsApp' ng-controller='cbsCnt as ct'>
    <cbs-cus-comp com-bind='ct.name'>
        <child child-com-bind='cbsCusCompCntAs.name'></child>
    </cbs-cus-comp>
</div>

我可以在组合中得到 ct.name 值。但无法在儿童组合中得到 cbsCusCompCntAs.name。(cbsCusCompCntAs is cbs-cus-comp controller)

工作升降机 : https://plnkr.co/edit/axQwTn?p=preview

提前谢谢。

在第一种情况下,您通过 controllerAs 直接引用控制器范围。

在 angular 1.5 中使用组件时,您可以通过require获取父组件,这将使父组件的属性在$onInit后根据组件文档可用:

请注意,在 控制器的实例化,但它们保证 在执行$onInit方法之前可用!

在特定情况下,您可以更新组件以要求父组件:

var child = {
    require     :  {parentComp:'^cbsCusComp'},
    template    :  'Child : <b{{cbsCusChildCompCntAs.childComBind}}</b>',
    controller  :  cbsCusChildCompCnt,
    controllerAs:  'cbsCusChildCompCntAs'
    };

及其控制器来获取您需要的数据(我使用了与您相同的名称只是为了看到它工作):

function cbsCusChildCompCnt(){
  this.$onInit = function() {
    this.childComBind = this.parentComp.name;
  };
}

更新的 plunker 在这里。

哇...多么好的例子...我花了一段时间来分析它...所以,我写了我自己的(我认为更具可读性)版本。我真的不知道如何使用Plunker...所以这是代码...从我的索引.html文件中提取

<div ng-controller='appCtrl as ctrl'>
    <parent bind-id='ctrl.name'>
        <child bind-toid='parentCtrlAs.name'></child>
    </parent>
</div>

.js文件

(function () {
'use strict';
var 
    parentComponent =   
    {
        bindings    :   
        {
            bindId:'='
        },
        controller  : parentCtrl,
        controllerAs: 'parentCtrlAs',
        restrict    : 'A',
        transclude  : true,
        templateUrl : 'parent.html',
    };
var 
    childComponent =    
    {
        controller  : childCtrl,
        controllerAs: 'childCtrlAs',
        restrict    : 'A',
        require     :
        {
            myParent    :'^parent'
        },
        templateUrl :   'child.html',
};

angular
    .module('app', [])
    .controller('appCtrl'   , appCtrl)
    .component('parent'     , parentComponent)
    .component('child'      , childComponent);

function appCtrl(){
    this.name = 'Main..';
}
function childCtrl(){
    this.$onInit = function() {
        this.bindToid = this.myParent.name;
    };
}
function parentCtrl(){
    this.name   =   'Parent Component';
}

})();

希望对您有所帮助,问候约翰尼

尽管使用"require"参数有效,但它在使用"require"参数的充当父组件和充当父组件(使用子功能)之间创建了紧密绑定的关系。

更好的解决方案是使用组件通信,如下所示。

基本上,您在子组件定义中定义一个绑定函数,如下所示:

angular.module('app').component('componentName', {
templateUrl: 'my-template.html',
bindings: {
       myFunction: '&'
},
controller: function() { // Do something here}
});

然后,在父标记中,您提供了一个要调用的函数,

父网页

<user-list select-user="$ctrl.selectUser(user)">
</user-list>

最后,在父控制器中,提供 selectUser 函数的实现。

这是一个工作的Plunk。