Angularjs: How can I run my custom directive after template compiled -
i writing custom directive , want directive access child element generated id in code below
<div class="my-directive" data-rawdata="user-{{user_id}}"> <div class="raw user-{{user_id}}" id="user-{{user_id}}" style='display:none'> i'm here. </div> </div>
this directive:
.directive('mydirective', [function(cart) { return { restrict: 'c', priority: -1000, link: function(scope, elem, attrs) { var element_id = attrs.rawdata if(element_id){ var found1 = angular.element("#" + element_id); // not found var found2 = angular.element("." + element_id); // not found var found3 = angular.element(".raw"); // found console.log( [found1.length, found2.length, found3.length] ); console.log( found3.attr('id') ); // -> still not compile = user-{{user_id}} ? console.log( found3.attr('class') ); // -> still not compile = user-{{user_id}} ? } } }; }])
and directive cannot access element id because it's not finish binding value of id yet.
is there way let directive execute after binding finish? tried priority -1000 no luck.
my plunker : http://plnkr.co/edit/2j7t6qk7f5mtywi64wpa?p=preview
wrap directive work in $timeout
. allows link code run after rendering completed, eg:
$timeout(function(){ if(element_id){ var found1 = angular.element("#" + element_id) var found2 = angular.element("." + element_id) var found3 = angular.element(".raw") console.log( [found1.length, found2.length, found3.length] ); console.log( found3.attr('id') ); // -> still not compile = user-{{user_id}} ? console.log( found3.attr('class') ); // -> still not compile = user-{{user_id}} ? if(found1.length) data = "your data " + found1.html() } angular.element(".result", elem).html( data || "data not found" ) }, 0);
also don't forget inject $timeout
directive.
Comments
Post a Comment