我遇到了一个问题。
我想创建带有分隔导航和内容的标签(每个标签都是一个单独的指令),它们使用事件互相交谈。
因此,导航指令非常简单,我没有在此处包含此部分。但内容对我来说要困难得多。我想只显示一个选定的选项卡并隐藏其他选项卡(基于父tabs
'范围内的某些变量)。每个选项卡都可以包含指令/表达式/普通html。我尝试了很多变种,但它们没有用。
您能帮我找一个解决方案吗?
如何将变量{{item.key}}
传递给ng-repeated ng-transcluded指令的属性?与<tab key="{{item.key}}" repeat="item in items">
如何从每个子选项卡的范围访问变量selectedTabKey
(即tabs
指令)?
var app = angular.module("app", []);
var $ = angular.element;
app.run(function($templateCache, $rootScope) {
$rootScope.items = [
{key:1,value:'a'},
{key:2,value:'b'},
{key:3,value:'c'}
];
});
app.directive( "tabs", function() {
return {
restrict: "AE",
scope: true,
transclude: true,
replace: true,
template: "<div ng-transclude></div>",
link: function(scope, elem, attr, ctrl) {
scope.selectedTabKey = 2;
// TODO: changing the selectedTabKey value
// want to show/hide the related tab
}
};
});
app.directive( "tab", function($compile) {
return {
restrict: "AE",
transclude: true,
replace: true,
template: "<div><span transclude></span></div>",
link: function( scope, elem, attr, ctrl, transclude ) {
var transc = $(elem[0].querySelector( "[transclude]" ));
transclude( scope, function( childs ) {
transc.append( childs );
});
transc.attr("ng-repeat", attr.repeat);
$compile(transc)(scope);
// todo: access parent's var `selectedTabKey`
// and make visible the related tab
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
<div ng-app="app">
<tabs>
<!-- how to pass the attr {{item.key}} below? -->
<tab key="{{item.key}}" repeat="item in items">
<!-- here some directive/expression/plain html -->
{{item.value}}
</tab>
</tabs>
</div>
答案 0 :(得分:1)
朋友, 你无法看到变量&#34; selectedTabKey&#34;在&#34; tab&#34;由于循环摘要的链接,你有两种选择:
Put&#34; tabs&#34;在之前运行的预链接中。
link: {
pre:function(scope, elem, attr, ctrl) {
scope.selectedTabKey = 2;
// TODO: changing the selectedTabKey value
// want to show/hide the related tab
}
}
<强> OR 强>
使用$ timeout
在下一个摘要周期中创建元素 app.directive( "tab", function($compile, $timeout) {
...
link: function( scope, elem, attr, ctrl, transclude ) {
...
$timeout(function(){
console.log(scope.$parent.selectedTabKey)
},0)
}
}
答案 1 :(得分:0)