Angular (1.5) Child 组件中 Parent 组件的 JS 访问变量?

Angular (1.5) JS Access Variable from Parent Component in Child Component?

我正在尝试使用 2 个组件将工单列表的概念抽象为 angular 应用程序。

第一个组件 --> ("Smart Component") 使用 $http 来提取数据并将其放入一个名为 populatedList 的数组中,该数组位于 parent ("gather")组件控制器。这部分有效。

第二个组件 --> ("Dumb component") 对于来自 parent 组件的 populatedList var 中的每个键值对,它应该创建一个列表项。 然而,第二个组件的 onInit() 函数从未被调用,即使我将它注册到同一个模块。当我通过浏览器查看时,HTML 模板代码没有实例化。我的控制台上没有收到任何错误,所以我做错了什么?为什么我的第二个组件不工作,即使我使用 "require" 从 parent 组件获取信息。

我终于得到了我的 child 组件来查看来自 pullTicketCtn 控制器的填充 "tickets" 变量的数据(由屏幕截图证明)但是当我尝试 console.log(vm.parentComp.tickets) 或 console.log(vm.tickets) 它给了我一个空数组,即使我只是做了 console.log(vm.parentComp) 和 console.log(vm)并通过控制台查看数组中的值。


所以现在 console.log(vm.parentComp.tickets) 和 console.log(vm) 都显示我的 displayTicketsCnt 和 pullTicketsCnt 控制器都有票据 var,但我无法在 child 或 console.log() 它。我究竟做错了什么?

pullticketCtn has the data/array

displayticketCtn has the data/array

第 3 张图片显示了 console.log(vm.parentComp) 的 2 个空数组 [] 和 [] 以及 console.log(虚拟机);

     /*COMPONENTS*/
     /*Parent/smart */
   var gather = {  
    controller:pullTicketsCnt,
    controllerAs:'pullTicketsCntAs',
    bindings: {
        tickets: '=',
        client_id:'='
    }      
};

/* Child/dumb component*/
var  list =  {  
    transclude  : true,
    require:{
        /* Require the parent component (^ means its an ancestor)*/
        parentComp:'^gather'
    },
    template: [
        '<ul class="main_list">',
         '<li ng-repeat:"(key, value) in displayTicketsCntAs.tickets">',
        '<span>{{key}}</span>',
     '</li>',
        '</ul>',
    ].join(''),
    controller:displayTicketsCnt,
    controllerAs:'displayTicketsCntAs',
};

/*CONTROLLERS */
function pullTicketsCnt($http){

        $http ...
        this.tickets=temp.slice(0); //Get the array of populated data
        ...
    }
}




 function displayTicketsCnt(){
  var vm = this;
        vm.$onInit = function(){
           console.log('LIST-DATA component initialized');
           console.log(vm.parentComp);
           console.log(vm);
           vm.populated= (vm.parentComp.tickets).slice(0);
           /*The two lines below print [] the empty arrays */
           console.log(vm.parentComp.tickets); 
            console.log(vm.populated);
        }




}


function listCtrl(){
    this.tickets=[];
}

/*Declarations */

var app = angular.module('ticket', [])
.controller('listCtrl',listCtrl) /* Assume this is correct*/
.component('gather',gather) 
.component('list',list);

/* HTML*/ 
 <div ng-app="ticket"  ng-controller="listCtrl as vm" class="ticket_controller">
           <gather tickets="vm.tickets">
             <list populated="pullTicketsCntAs.tickets"></list>
            </gather>
        </div>  

transclude : true,应该是收集的一部分而不是列表。

您可以使用

访问 parent 控制器

要求:{ parent: '^^聚集' },