2

I am trying to create a pagination directive. When total_for_pagination is populated, the proper HTML for the pagination is created.

My html: max = max per page

<pagination data-number="{{ total_for_pagination }}" data-max="50"></pagination>

My directive:

    link: function(scope, element, attrs){
        scope.$watch(function(){return attrs.number;}, function(){
            //Need to watch because there is a query to db to know how many elements to page.
            var page_element = '<ul>';
            for(var i = 0; i*attrs.max<attrs.number; i+=1){
                page_element += '<li class="pagination"><a ui-sref="users({start: '+i*attrs.max+', end: '+((i*attrs.max)+(attrs.max-1))+'})">'+i+'</a></li>';
            }
            page_element += '</ul>';
            element.append(page_element);
        });
    }

What is happening is that when I inspect my html they are as they should be but ui-sref is note changing the state when I click on it. When I just place the same code, works fine.

What I am doing wrong? Thanks!

Colin Brock
  • 21,267
  • 9
  • 46
  • 61
Rodrigo Pereira
  • 1,834
  • 2
  • 17
  • 35

2 Answers2

3

What we need here, is to use the angular js core feature: $compile. See that in action in this working example. This is the line with the trick: $compile(element.contents())(scope);

That could be the directive definition:

.directive("myDirective", function($compile){
  return {
    restrict: 'A',
    link: function(scope, element, attrs){
        scope.$watch(function(){return attrs.number;}, function(){
            var page_element = '<ul>'
            +'<li><a ui-sref="home">ui-sref="home"</a></li>'
            +'<li><a ui-sref="other">ui-sref="other"</a></li>'
            + '</ul>';
            element.append(page_element);
            $compile(element.contents())(scope);  
        });
    }
  }
})

which for these states:

  .state('home', {
    url: "/home",
    templateUrl: 'tpl.html',
  })
  .state('other', {
    url: "/other",
    templateUrl: 'tpl.html',
  })

Will do what we need. Check it here. See also a bit related: Form Validation and fields added with $compile

Community
  • 1
  • 1
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
0

One way it worked for me is to declare an array in controller/directive and use ng-repeat in html li's. Update the array dynamically and the elements get updated automatically and ui-sref also works. If not, try $scope.apply then.

yeswanth
  • 1,543
  • 1
  • 11
  • 19