如何让ui-sref通过element.append动态工作?

时间:2014-11-07 04:32:47

标签: javascript angularjs angular-ui-router

我正在尝试创建一个分页指令。 填充total_for_pagination时,会创建适当的分页HTML。

我的html:max =每页最多

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

我的指示:

    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);
        });
    }

发生的事情是,当我检查我的html时,他们应该是他们应该的,但是当我点击它时,ui-sref会改变状态。当我只是放置相同的代码,工作正常。

我做错了什么? 谢谢!

2 个答案:

答案 0 :(得分:3)

我们需要的是使用角度js核心功能:$compile。请参阅this working example中的实际操作。这就是技巧: $compile(element.contents())(scope);

这可能是指令定义:

.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);  
        });
    }
  }
})

对于这些状态:

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

将做我们需要的事情。检查here。另请参阅:Form Validation and fields added with $compile

答案 1 :(得分:0)

它对我有用的一种方法是在控制器/指令中声明一个数组,并在html li中使用ng-repeat。动态更新数组,元素自动更新,ui-sref也可以。如果没有,请尝试$ scope.apply。

相关问题