Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

javascript - {{$index}} of ng-repeat computed after linker function of angular directive. $compile it?

html

<div repeater ng-repeat='item in items' class='first' id = '{{$index}}' > {{item}} </div>

angularjs directive:-

angular.module('time', [])
  .directive('repeater', function() {

    var linkFn = function(scope, element, attrs){
      var id = $(element).attr('id');
      alert(id); // {{$index}}
    } ...

dynamic id created inside ng-repeat, when evoked inside directive displays as {{$index}} instead of value = 0, 1, 2 ...

How do you ensure when Linker function in directive executes the dynamic ids are used? I think it can be done using $compile inside the directive. But i can't quite figure how?

$compile(element)(scope) 

is the syntax. But obviously the wrong order.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you really need the IDs to be already populated you can run the relevant code inside scope.$evalAsync or $timeout to make sure the binding has been updated first. I would suggest trying hard to avoid needing to inspect the DOM and relying instead on your model for any of this information, using scope.$index.

Your directive is already in the process of being compiled when and linked when your link function is reached so I think recompiling wouldn't help. It is just a case of waiting long enough to finish the linking and start a $digest where the attributes will actually be updated. This is exactly what $evalAsync will do for you.

Example here: http://plnkr.co/edit/n77x4C?p=preview


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...