Angularjs编写选项卡

时间:2021-12-01 06:25:31

我们以某招聘网站的岗位分类为例。
Angularjs编写选项卡
我们先查看一下我们请求到的json数据。

company.json

{
"id": "c1",
"imageUrl": "/image/company-1.png",
"name": "XX网",
"industry": "移动互联网",
"state": "A轮",
"people": "50-150人",
"positionClass": [{
"id": "jishu",
"name": "技术",
"positionList": [{
"id": "p1",
"name": "IOS前端工程师",
"createdDate": "2016-04-16 23:30",
"salary": "15k-25k"
}]
}, {
"id": "yunying",
"name": "运营",
"positionList": [{
"id": "y1",
"name": "运营总监",
"createdDate": "2016-04-10 13:30",
"salary": "25k以上"
}]
}]
}

company.html页面

<div app-head-bar text="公司职位"></div>
<div app-company com="company"></div> //给指令声明com的接口
<div app-position-class com="company"></div>//给指令声明com的接口

companyCtrl.js控制器

'use strict';
angular.module('app').controller('companyCtrl',
['$http', '$state', '$scope', function($http, $state, $scope){
$http.get('data/company.json?id='+$state.params.id).
success(function(resp){
$scope.company = resp;//将请求的结果传给company的属性
});
}]);

positionClass.js指令

'use strict';
angular.module('app').directive('appPositionClass', [function(){
return {
restrict: 'A',
replace: true,
scope: { //声明接口
com: '='
},
templateUrl: 'view/template/positionClass.html',
//④添加指令逻辑
link: function($scope) {
$scope.showPositionList = function(idx) {
$scope.positionList = $scope.com.positionClass[idx].positionList;
//⑤把索引值传给isActive
$scope.isActive = idx;
}
//⑦所以监控com属性,传入函数,监控这个属性改变之后的值,
$scope.$watch('com',function (newVal) {
//⑥添加默认选中按钮,但是报错了,因为我们在调用showPositionList(0)这个函数的时候,com对象并没有传入,控制器还在发送ajax请求等待返回的过程,这个时候可能appPositionClass指令就已经加载了,正确的做法是当com传入过来以后,再调用这个函数,来对这个指令进行初始化,默认选中第一个
//⑧只要第一个值存在的时候,就调用这个函数,对指令进行初始化
if(newVal) $scope.showPositionList(0);
});
}
};
}]);

positionClass.html指令模板

<div class="position-class">
<h5>职位分类</h5>
<button ng-click="showPositionList($index)" class="
{{$index===isActive?'active':''}}" ng-repeat="cls in com.positionClass" ng-bind="cls.name"></button>
<!--
①使用ng-repeat指令来创建重复的DOM元素.
②使用ng-bind指令绑上相关数据,
③ng-click="showPositionList($index)" class="
{{$index===isActive?'active':''}}
添加点击事件和样式,点事件传入当前索引值,当按钮是当前索引值的时候添加active样式

-->


<ul>
<li class="p-r" ng-repeat="pos in positionList">
<p ng-bind="pos.name"></p>
<p ng-bind="pos.createdDate"></p>
<span ng-bind="pos.salary" class="p-a"></span>
</li>
</ul>
</div>