Angularjs compile ng controller and interpolation

In docs, I saw an example of the compilation of something added later.

var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>'); $(document.body).append($div); angular.element(document).injector().invoke(function($compile) { var scope = angular.element($div).scope(); $compile($div)(scope); }); 

I added this code to the jquery ready function, but I have two problems:

First an error occurs: Argument 'MyCtrl' is not a function, got undefined .

Secondly, I do not know how to make content.label work! I added it to scope , but it does not work. How do I call my controller to see how content.label data binding works?

MY FINAL MODIFIED CODE:

 var app = angular.module('app',[]); $(function(){ app.controller('MyCtrl',function($scope){ $scope.content = 123; }); var $div = $('<div ng-controller="MyCtrl">{{content}}</div>'); $(document.body).append($div); angular.element(document).injector().invoke(function($compile) { var scope = angular.element($div).scope(); $compile($div)(scope); }); }); 
+5
source share
1 answer

UPDATE

You must start the digest cycle after compiling the new markup to create all the bindings and fire watchers. This can be done by calling scope.$digest(); :

 $compile($div)(scope); scope.$digest(); 

The result should look like this:

 var app = angular.module('app',[]); app.controller('MyCtrl',function($scope){ $scope.content = 123; }); angular.element(document).ready(function () { var $div = $('<div ng-controller="MyCtrl">{{content}} </div>'); $(document.body).append($div); angular.element(document).injector().invoke(function($compile) { var scope = angular.element($div).scope(); $compile($div)(scope); scope.$digest(); }); }); 

http://plnkr.co/edit/dDNBxf8SowKTPgnVj0tF?p=preview

+3
source

Source: https://habr.com/ru/post/1236342/


All Articles