在學習angular的過程中,實踐是最好的方法。
在開發選項卡的過程中,不需要再像jquery一樣以DOM操作為核心,那什么樣的情況是以DOM操作為核心的Jquery的思想呢?
一想到改變什么,就想設置ID,獲取元素。這就是jquery的思想。
angular的思想是一切以數據為中心,在controller中只操作數據,不去處理其他的問題。只改變數據的邏輯,不對界面進行操作。不設置class,不操作DOM,不做與界面元素有關的事情。做好分層設計,在每層做每層該干的事情。
選項卡代碼:
css部分代碼(隨便寫的,需要的自己寫)
*{ margin:0;padding:0;}
#btn_group{list-style:none; margin:0 auto; width:850px;}
#btn_group li{ width:200px; height:40px; line-height:40px; border:1px solid black; float:left; margin:5px; text-align:center;}
#content{ width:800px; height:800px; border:1px solid black; overflow:hidden; clear:both; margin:0 auto; position:relative;}
#content div{ position:absolute; top:0; left:0;}
.btn_in{ background:blue;}
.selected {background-color: lightgreen;}
.hide{display:none;}
.show{display:block;}
html結構:
ng-repeat的li是可以作為代替this來傳遞的,它引用的是你本身的原始數據,所以在ng-class中也可以做判斷,li是否等於你選擇的tab。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<title>angularjs 選項卡</title>
<script type="text/javascript" src="angular.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtr">
<ul id="btn_group">
<li ng-repeat="li in lis" ng-click="show($index,li.links)" ng-class="{selected: $index==selected}">
{{li.name}}
</li>
</ul>
<div id="content" >
<div ng-repeat="div in divs" class="hide" ng-class="{show:$index==selected}">{{div.html}}</div>
</div>
</body>
</html>
js關鍵代碼:
這里以selected作為頁面和tab之間的聯系樞紐,形成映射關系。通過ng-repeat的$index和ng-class的key-value值方法來做一個判斷。
var app=angular.module('myApp',[]);
app.controller('myCtr',function($scope){
//$scope.res={link:'no.html'};
//這里的link是為了你在頁面引入模板而寫的,這里沒有引入模板,是假數據divs
$scope.selected=0;
$scope.lis=[{name:'按鈕一',links:'no.html'},{name:'按鈕二',links:'or.html'},{name:'按鈕三',links:'and.html'},{name:'按鈕四',links:'xor.html'}];
$scope.divs=[{html:'我是頁面一'},{html:'我是頁面二'},{html:"我是頁面三"},{html:"我是頁面四"}];
$scope.show=function(row,str){
$scope.selected=row;
//$scope.res.link=str;
}
});