![](/img/trans.png)
[英]use @Attribute in custom attribute directive and data -binding attribute directive
[英]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.