angualr 实现tab选项卡功能

时间:2022-05-07 07:46:41

tab.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body ng-app="myApp">
<div ng-controller="myCtr">
<div my-title data="data"></div>
</div> <script src="angular.min.js"></script>
<script src="jquery-3.1.1.min.js"></script>
<script>
var app = angular.module("myApp", [])
app.controller('myCtr', ["$scope",function($scope){
$scope.data = [
{title:"英雄联盟",data:[
{title:"诺克"},
{title:"剑圣"}
]},
{title:"王者荣耀",data:[
{title:"刘备"},
{title:"兰陵王"}
]}
];
}]);
app.directive('myTitle', function(){
return {
restrict: 'EA',
templateUrl: 'time.html',
scope: {data:'=data'},
link: function(scope, elem, attr){ //link用来操作DOM元素
$(elem).delegate('a', 'click', function(){ //外部文件的元素绑定事件要用live\on\delegate,根据jquery版本来选
$('a').removeClass('active'); //移除a标签class
$(this).addClass('active'); //为当前元素添加类
var index = $(this).index(); //获取序号index
$(elem).find("div.list").hide();
$(elem).find("div.list").eq(index-1).show(); //eq()方法获取索引,所以index需 -1
});
}
}
});
</script>
</body>
</html>

time.html

  • 父元素ng-repeath后,子元素ng-repeat才有效

<div class="tab">
<style>
.tab a { text-decoration: none; display: inline-block; border: 1px solid #ccc;}
.tab div {border: 1px solid #ccc; width:200px; height:200px; margin: 0;}
.active {background-color: #aaa; color: #fff;}
</style>
<a ng-repeat="v in data" href="#" ng-class="{active:$first}">{{v.title}}</a>
<div ng-repeat="v in data" ng-style="{display: $first?'block':'none'}" class="list"> <!-- 父元素ng-repeat -->
<ul>
<li ng-repeat="m in v.data">{{m.title}}</li> <!-- 子元素ng-repeat -->
</ul>
</div>
</div>