簡體   English   中英

使用angular指令作為自定義指令的屬性

[英]Use angular directive as attribute of custom directive

我正在嘗試編輯這位先生的小提琴( http://jsfiddle.net/Wijmo/ywUYQ/ ),以將ng-click功能添加到窗格中。

我的目標是向窗格指令添加ng-click函數,以便在單擊該指令時運行指定的動作。

例:

<tabs>
    <pane ng-repeat="candy in candies" title="Tasty {{candy.name}}" ng-click="addChocolate(candy)">
</tabs>

您將在代碼段中看到通過調用選項卡控制器中的addPane並將其自身添加到其窗格列表中, 窗格指令可以正常工作。 tabs指令負責處理click事件並顯示正確的窗格 所以.....有什么想法嗎?

這是小提琴中顯示的摘錄:

 angular.module('components', []) .directive('tabs', function() { return { restrict: 'E', transclude: true, scope: {}, controller: ["$scope", function($scope) { var panes = $scope.panes = []; $scope.select = function(pane) { angular.forEach(panes, function(pane) { pane.selected = false; }); pane.selected = true; } this.addPane = function(pane) { if (panes.length == 0) $scope.select(pane); panes.push(pane); } } ], template: '<div class="tabbable">' + '<ul class="nav nav-tabs">' + '<li ng-repeat="pane in panes" ng-class="{active:pane.selected}">' + '<a href="" ng-click="select(pane)">{{pane.title}}</a>' + '</li>' + '</ul>' + '<div class="tab-content" ng-transclude></div>' + '</div>', replace: true }; }) .directive('pane', function() { return { require: '^tabs', restrict: 'E', transclude: true, scope: { title: '@' }, link: function(scope, element, attrs, tabsCtrl) { tabsCtrl.addPane(scope); }, template: '<div class="tab-pane" ng-class="{active: selected}" ng-transclude>' + '</div>', replace: true }; }) 
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app="components"> <h3>BootStrap Tab Component</h3> <tabs> <pane title="First Tab"> <div>This is the content of the first tab.</div> </pane> <pane title="Second Tab"> <div>This is the content of the second tab.</div> </pane> </tabs> </body> 

當您的指令返回窗格的HTML時,Angular不會編譯ng-click=... 您可以使用$compile服務來編譯pane指令的輸出HTML,以便Angular可以將您的回調注冊為onclick事件的處理程序。

在鏈接函數中,輸出HTML的處理方式如下: $compile(html)(scope)

您可以嘗試這樣的事情:

.directive('pane', function() {
return {
  require: '^tabs',
  restrict: 'E',
  transclude: true,
  scope: {
    title: '@',
    paneClick: '=',
    paneClickAttr: '='
  },
  link: function(scope, element, attrs, tabsCtrl) {
    tabsCtrl.addPane(scope);
  },
  template: '<div ng-click="paneClick(paneClickAttr)" class="tab-pane" ng-class="{active: selected}" ng-transclude>' +
    '</div>',
  replace: true
};})


<pane title="First Tab" pane-click="addChocolate()" pane-click-attr="candy">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM