2

所以我一直试图弄清楚过去4个小时。基本上,我有被动态编译成DOM 父指令,并在其中我有被transcluded要求组件的控制器返回一个空控制器

$compile('<edit-modal entry="entry" positions="positions" day="day" is-filled="isFilled" week-start-date="weekStartDate" available-tags="availableTags" minigrids="minigrids">' + 
     '<ns-gap-requests gap="entry" minigrids="minigrids"></ns-gap-requests></edit-modal>')(scope); 

组件以下是该组件在editModal HTML渲染:

<div id="gapRequestsBody" ng-if="onGapRequest" ng-transclude></div> 

以下是我的父母指令

return { 
     restrict: 'E', 
     replace: 'true', 
     transclude:"true", 
     templateUrl: 'Scripts/NewScheduler/Templates/Modals/editModal.html', 

     scope: { 
      positions: '<', 
      entry: '=', 
      day: '<', 
      weekStartDate: '<', 
      availableTags: '<', 
      minigrids: '<' 
     }, 

     controller: ['$scope', '$element', function ($scope, $element) { 
      $scope.$parent.child = $scope; 

      $scope.onGapRequest = false; 
      $scope.changeToOnGapRequestPage = function() { 
       $scope.onGapRequest = true; 
      } 

.....

以下是我的孩子组成:

(function() { 
    'use strict'; 

    angular.module('newScheduler').component('nsGapRequests', 
     { 
      require:{editModalCtrl : "^editModal"}, 
      bindings: { 
       gap: "=", 
       minigrids:"<" 
      }, 
      templateUrl: "Scripts/NewScheduler/Templates/Modals/nsGapRequestsModal.html", 
      controller: [function() { 
       var self = this; 

       self.$onInit = function() { 
        console.log(self); 
       } 

       console.log(self.gap); 
       console.log(self.minigrids); 

       if (!self.assignToOption) { 
        self.assignToOption = { chosenRequester: null }; 
       } 

       self.requesters = self.minigrids.map(function (minigrid) { 
        return minigrid.gridRows; 
       }).reduce(function(a, b) { 
        return a.concat(b); 
       }) 
        .map(function (gridRows) { 
        return gridRows.user; 
        }) 
       .filter(function (value, index, array) { 
        return array.indexOf(value) === index; 
       }) 
       .filter(function(user) { 
        return self.gap.requests.indexOf(user.id) !== -1; 
        }); 

      }], 
      controllerAs: "gapRequests" 
     }); 
})(); 

但我不明白为什么我不能访问父控制器: console log of the child component members

,由于某种原因editModalCtrl是空的(但不应该!)

我真的很感激,如果有人能帮助我。 干杯。

回答

1

控制器实际上不是空的,你只是没有定义它的任何属性/方法。您正在使用$scope来代替。尝试添加一些成员,并检查:

controller: ['$scope', '$element', function ($scope, $element) { 
    var self = this; 
    self.someMember = true; 
    self.someMethod = function() { 
    } 
} 
+0

哦,你是对的。感谢堆。但是有一个问题。我认为当你将指令的控制器与另一个指令/组件共享时,你实际上正在共享范围,这不是真的吗? –

+0

不,除非您以某种方式明确暴露它。你也可以直接绑定到控制器,而不是使用$ scope。 –

相关问题