简体   繁体   中英

Pass an Angular variable to the directive

I'm building a pagination in angular, here is my directive:

app.directive('postsGenreLink', function() {
    return {
        restrict: 'EA',
        templateUrl: myLocalized.partials + 'posts-genre-link.html',
        controller: ['$scope', '$element', '$routeParams', function($scope, $element, $routeParams) {
            var currentGenrePage = (!$routeParams.page) ? 1 : parseInt($routeParams.page),
                linkPrefix = (!$routeParams.slug) ? 'page/' : 'genre/' + $routeParams.slug + '/page/';

            $scope.postsGenreLink = {
                prevLink: linkPrefix + (currentGenrePage - 1),
                hopLink: linkPrefix + (currentGenrePage),
                nextLink: linkPrefix + (currentGenrePage + 1),
                sep: (!$element.attr('sep')) ? '|' : $element.attr('sep'),
                prevLabel: (!$element.attr('prev-label')) ? 'Previous Page' : $element.attr('prev-label'),
                nextLabel: (!$element.attr('next-label')) ? 'Next Page' : $element.attr('next-label'),
                hopLabel: (!$element.attr('Jump')) ? 'Jump' : $element.attr('Jump')
            };
        }]
    };
});

and here is the posts-genre-link.html I want to display:

<nav aria-label="...">
  <ul class="pagination pt-3">
    <li class="page-item" ng-class="{'disabled' : currentGenrePage == 1}">
      <a class="page-link" href="{{postsGenreLink.prevLink}}">Previous</a>
    </li>
    <li ng-repeat="i in [].constructor(totalPages) track by $index" class="page-item" ng-class="{'active' : currentGenrePage == $index + 1}"><a class="page-link" href="{{postsGenreLink.hopLink}}">{{$index + 1}}</a></li>

    <li class="page-item" ng-class="{'disabled' : currentGenrePage >= totalPages}">
      <a class="page-link" href="{{postsGenreLink.nextLink}}">Next</a>
    </li>
  </ul>
</nav>

It works great except for the href inside the ng-repeat . I would like that hopLink is the value of linkPrefix plus $index + 1 . How can I achieve this?

I've fixed this changing the hopLink to hopLink: linkPrefix, and inside the href I did: href="{{postsGenreLink.hopLink}}{{$index + 1}}" . This was way more simple than passing the $index value to the controller through a ng-click.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM