angularjs - Nested directive life-cycle not executing in expected order when using $compile and adding to the DOM for the first time -
what i'm trying do
i have following directive structure:
<dashboard> <widget> <timer></timer> </widget> <widget> <chronometer></chronometer> </widget> </dashboard> where dashboard, widget, timer, , chronometer custom directives i've written.
the basic idea want dashboard directive keep track of widgets has. when widget $compiled , added dom dashboard, automatically adds dashboard calling addwidget(widget) method widget's link function, exposed dashboard's controller.
the widget directive knows how minimize itself, close itself, set title, etc., , has register method on controller takes in widget metadata information (e.g., name , version of widget).
the timer , chronometer widgets require widget , call register({name: 'timer', version: '0.1'})' exists in thewidget`'s controller function.
finally, there addwidget() method in dashboard's link function allows users add timer , chronometer widgets dashboard.
for example, i'm going assume want add timer directive dashboard:
// dashboard.directive.js function link($scope, $elem, $attrs) { $scope.addwidget = function () { var widget = $compile('<widget><timer></timer></widget>')($scope); angular.element($elem[0].queryselector('.widget-container')).append(widget); } } when $addwidget function called, timer widget added dashboard, can start/stop/reset timer, , widget directive registers timer directive, , widget directive registers dashboard directive. i've 100% confirmed working perfectly.
directive life-cycle: i'm expecting
as reminder, here's how dom looks like:
<dashboard> <!-- dashboard exists on initial bootstrap --> <widget> <!-- widget , timer added dynamically dashboard --> <timer></timer> </widget> <widget> <!-- widget , chronometer added dynamically dashboard --> <chronometer></chronometer> </widget> </dashboard> from understand of angular directives' life-cycle, directives should constructed follows:
dashboard controller() called dashboard link() called widget controller() called timer controller() called timer link() called widget link() called where widget , timer added dom within dashboard described in dashboard.directive.js snippet above.
directive life-cycle: i'm getting (sometimes)
however, when add timer dashboard first time, not case. after added bunch of console.log statements inside controller , link functions dashboard, widget , timer directives, however, found directives being constructed in order:
dashboard controller() called dashboard link() called // why happening: widget controller() called widget link() called timer controller() called timer link() called what's more puzzling seemingly out-of-order composing happens first time add widget dom. second time add same widget, happens in correct order.
what doing wrong? i'm using angular 1.2.26 (i required use version, unfortunately). :)
Comments
Post a Comment