[英]How to call different functions from different controllers on the click of each tab in angular ui tabs?
我試圖使用angular-ui
tabs directive
在每個選項卡的單擊上調用不同控制器的不同函數。
HTML
<tabset>
<tab heading="Reports" ng-controller="ReportsController" ng-click="fetchReports()" id="tab1">
<div> Reports </div>
</tab>
<tab heading="Sales" ng-controller="SalesController" ng-click="fetchSales()" id="tab2">
<div> Sales </div>
</tab>
</tabset>
我收到這樣的錯誤
要求新/隔離范圍的多個指令[ngController,tab]
需求
I have 5-6 tabs in a page. The page should not load the data of each tab at once. It should only load data for a tab once that tab is being clicked.
解
我有一個解決方案來使用parent controller
包裝tabset
指令,以便我可以從ParentController
broadcast
事件以從相應的Child
控制器調用函數。
<div ng-controller='ParentController'>
<tabset>
<tab heading="Reports" id="tab1">
<div ng-controller="ChildOneController"> Reports </div>
</tab>
<tab heading="Sales" id="tab2">
<div ng-controller="ChildTwoController"> Sales </div>
</tab>
</tabset>
</div>
問題:
但遺憾的是,我的應用程序中有太多帶有選項卡的頁面,我不認為從ParentController
到ChildController
每個選項卡的廣播事件是個好主意。 我需要知道什么應該是一個很好的解決方案呢?
您可以使用控制器作為語法:
<div ng-controller="ReportsController as reports">
<div ng-controller="SalesController as sales">
<tabset>
<tab heading="Reports" ng-click="reports.fetchReports()" id="tab1">
<div> Reports </div>
</tab>
<tab heading="Sales" ng-click="sales.fetchSales()" id="tab2">
<div> Sales </div>
</tab>
</tabset>
</div>
</div>
以下是控制器的外觀示例:
(function(){
angular
.module('app')
.controller('ReportsController', [
ReportsController
]);
function ReportsController() {
var vm = this;
vm.fetchReports = function () {
// fetch the reports!
};
}
})();
來源:John Papa的角度風格指南建議使用控制器作為超過$ scope的語法,請參閱樣式指南 。
在你的情況下,
你應該創建一個指令 :
通過這種方式,您可以使用
loop
來創建具有多個控制器的多重指令。
(function() { angular .module('app') .diretive('directiveTab', function() { return { restrict: 'AE', template: " <div> Reports </div>"//you can use templateUrl as well scope: {}, controller: ['$scope', function($scope) { $scope.function1 = function(pane) { }; } ], }; } })
the directive will behave like controller and you can manipulate the content of each tab <div ng-controller='ParentController'> <tabset> <tab heading="Reports" id="tab1"> <directive-tab> </tab> </tabset> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.