2017-06-01 84 views
0

如果我有兩個指令,一個是表格,另一個是連續的。在這種情況下,每一行都是相同的,我只想讓它在index.html中顯示兩次。 <table-row>工程在index.html中,但<table>不是爲什麼?使用ControllerAs語法的指令中的自定義指令

即:

.directive('table', function() { 
    return { 
    restrict: 'E', 
    scope: {}, 
    controller: 'table-ctrl', 
    controllerAs: 'ctrl', 
    bindToController: true, 
    template:` 
     <div> 
     <table-row></table-row> 
     <table-row></table-row> 
     </div>` 
    }; 
}); 

錶行:

.controller('TableRowCtrl', function() { 
    this.toggle = function() { 
    this.toggleBool = !this.toggleBool; 
    } 
    // 
    this.toggleBool = false; 
}) 

.directive('TableRow', function() { 
    return { 
    scope: {}, 
    restrict: 'E', 
    replace: true, 
    controller: 'TableRowCtrl', 
    controllerAs: 'ctrl', 
    bindToController: true, 
    template: ` 
     <div> 
     <span>Object</span> 
     <span> 
      <img ng-click="ctrl.toggle()" src="jpeg file" /> 
     </span> 
     <span ng-if="ctrl.toggleBool"> Print </span> 
     </div>` 
    }; 
}); 

如果table-row是其他指令,做一切和它的控制器也什麼對點擊次數等運行時,我將如何在table-row鏈接指令,以便table指令模板能夠正常工作,並且會多次呼叫table-row.I想繼續使用ControllerAs語法而不是$scope

+0

請仔細閱讀本https://docs.angularjs.org/guide/directive明確 –

回答

0

無論您是否想要使用controllerAs都沒關係。從你的代碼table指令已經隔離範圍,並假設如果你想通過使用ngRepeat指令遍歷table-row項目,它應該也是隔離範圍。

請記住,每一個ngRepeat的項目有自己的範圍

例如:

.directive('table', function() { 
    return { 
    restrict: 'E', 
    scope: {}, 
    controller: 'table-ctrl', 
    controllerAs: 'ctrl', 
    bindToController: true, 
    template: 
     <div ng-repeat="item in ctrl.items"> 
     <table-row item="item"></table-row>   
     </div>` 
    }; 
}); 
+0

你應該解釋清楚可以溝通的指令 –

+0

所以在這種情況下,應該是每次都是同樣的事情,我只是想嘗試打印兩次。但是當我使用

來運行index.html時,它不起作用,但是如果我使用它確實有效。 – user3628240

+0

@ user3628240您可以創建數百個''物品,每個物品都有自己的範圍。 –