javascript - Angular Delayed Compilation Skipping ng-bind -
background
you can invoke $compile
after angular application has been bootstrapped using angular.injector
method.
angular.injector(['ng', 'late']).invoke(function($rootscope, $compile) { $compile(myelement)($rootscope) }
this works fine directives have created on late
module, not invoke of ng-bind
.
example
i have angular app initialized on element separate ones need compile.
<div ng-app="test"> </div> <div id="uncompiled"> {{ $id }} <div ng-controller="latecontroller cont"> {{ $id }} {{ "5" }} {{ cont.clicked }} <div late-directive="5"></div> </div> </div>
then, once angular finished bootstrapping, create module , directives elements should compiled late.
angular.element(document).ready(function() { angular.module('late', []) angular.module('late').controller('latecontroller', function($scope) { console.log('make controller', $scope) $scope.latecontroller = true this.clicked = 6 }) angular.module('late').directive('latedirective', function() { console.log('make directive') return { restrict: 'a', template: '<span>innerest {{ $id }}</span> compiled late!!! {{ $id }} {{ cont.clicked }}', } }) angular.injector(['ng', 'late']).invoke(function($compile, $rootscope) { console.log('injecting') var el = angular.element(document.getelementbyid('uncompiled')) $compile(el)($rootscope) }) })
play around code or view output.
if notice, of {{ }}
ng-binds not replaced directive template (latedirective
) inserted document.
question
why directives work , others not?
how can of directives work inside delayed $compile
?
the key why occurs demonstrated adding 1 simple line of html. if add element latecontroller
<input ng-model="cont.text" />
then whole example works intended. why adding ng-model effect other directives? behavior suggests other directives getting executed; aren't outputting values screen.
in normal angular application, after set up, application runs $digest
cycle. however, when using $injector.invoke
, $digest
cycle not run automatically.
the reason example worked when ng-model added ng-model runs $digest
.
solution: add $rootscope.$digest()
@ end of invoke
.
Comments
Post a Comment