Skip to content

Instantly share code, notes, and snippets.

@tyllo
Created May 30, 2016 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tyllo/846ef18d3392321e553c3177cdb87a3d to your computer and use it in GitHub Desktop.
Save tyllo/846ef18d3392321e553c3177cdb87a3d to your computer and use it in GitHub Desktop.
Example Angular derictive
class PaginationDirective {
constructor () {
this.restrict = 'E'
this.replace = true
this.templateUrl = 'common/directives/mb-pagination'
this.scope = {
currentPage: '=',
countPage: '=',
selectPage: '=',
url: '='
}
}
compile () {
return this.link.bind(this)
}
link ($scope/*, $el, attrs*/) {
this.$scope = $scope
$scope.pages = this.pages($scope.countPage)
$scope.prevPage = this.prevPage.bind(this)
$scope.nextPage = this.nextPage.bind(this)
$scope.createUrl = this.createUrl.bind(this)
}
prevPage () {
var currentPage = this.$scope.currentPage
return currentPage > 1 ? currentPage - 1 : currentPage
}
nextPage () {
var {currentPage, countPage} = this.$scope
return currentPage < countPage ? currentPage + 1 : currentPage
}
createUrl (page) {
if (!/page=\d/i.test(this.$scope.url)) {
return `${ this.$scope.url }&page=${ page }`
}
return this.$scope.url.split('&').map(item => {
return /page=\d/i.test(item) ? `page=${ page }` : item
}).join('&')
}
pages (count) {
var arr = []
for (var i = 0; i < count; i++) {
arr[i] = i + 1
}
return arr
}
}
app.directive('mbPagination', () => {
return new PaginationDirective()
})
.pagination {
display: inline-block;
padding-left: 0;
margin: 1rem 0;
border-radius: 2px;
> li {
display: inline;
}
}
.pagination-link {
position: relative;
float: left;
padding: .5rem .75rem;
line-height: 1rem;
text-decoration: none;
color: #428bca;
background-color: #FFF;
border: 1px solid #ddd;
margin-left: -1px;
&.active {
color: #FFF;
background-color: #428bca;
cursor: default;
}
&.disabled {
color: #428bca;
background-color: #b3d1ea;
cursor: no-drop;
}
li:first-child > & {
margin-left: 0;
border-left-radius: .5rem;
}
li:last-child > & {
border-right-radius: .5rem;
}
&:not(.disabled):not(.active):hover {
z-index: 3;
background-color: #EEE;
border-color: #428bca;
cursor: pointer;
}
}
<nav>
<ul class="pagination">
<li>
<a
class="pagination-link"
ng-class="{disabled: prevPage() === currentPage}"
ng-href="{{ createUrl(prevPage()) }}"
ng-click="selectPage(prevPage(), $event)"
href="#"
>
<span>&laquo;</span>
</a>
</li>
<li ng-repeat="page in pages">
<a
class="pagination-link"
ng-class="{active: currentPage === page}"
ng-href="{{ createUrl(page) }}"
ng-click="selectPage(page, $event)"
ng-bind="page"
></a>
</li>
<li>
<a
class="pagination-link"
ng-class="{disabled: nextPage() === currentPage}"
ng-href="{{ createUrl(nextPage()) }}"
ng-click="selectPage(nextPage(), $event)"
>
<span>&raquo;</span>
</a>
</li>
</ul>
</nav>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment