繁体   English   中英

如何在角度ui选项卡中单击每个选项卡,从不同的控制器调用不同的功能?

[英]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>

问题:

但遗憾的是,我的应用程序中有太多带有选项卡的页面,我不认为从ParentControllerChildController每个选项卡的广播事件是个好主意。 我需要知道什么应该是一个很好的解决方案呢?

您可以使用控制器作为语法:

<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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM