{{model.name}...">

$ compile (html) (scope) ignores the scope I created manually

Here is my code:

HTML:

<div id="container" ng-controller="MyCtrl"> {{model.name}} </div> 

JavaScript:

 var app=angular.module('myApp', []); var $injector =angular.injector(['ng']); $injector.invoke(function($compile, $rootScope) { var html = '<div ng-controller="MyCtrl1">{{model.name}}</div>' var scope = $rootScope.$new(); scope.model = {name:'MyCtrl1'}; //alert(scope.model.name); var e3 = $compile(html)(scope); $('#container').append(e3[0]); }); function MyCtrl($scope) { $scope.model={}; $scope.model.name = 'MyCtrl'; }; function MyCtrl1($scope) { //alert('MyCtrl1'); }; 

Here is a fiddle showing behavior

As you can see, it displays two lines of "MyCtrl". That is, angular ignores the scope object that I created manually.

The question arises: how to make $compile use the created area?


UPDATE: A terrible workaround:

After calling $compile apply the model again:

 angular.element(e3[0]).scope().$apply(function(scope) { scope.model = {name:'MyCtrl1'}; }); 
+4
source share
1 answer

ng-app creates an injector, then you create another one. This is probably not what you want. I moved most of your code to the run () method, in which $ compile service and $ rootScope were introduced:

 app.run(function($compile, $rootScope) { var html = '<div ng-controller="MyCtrl1">{{model.name}}</div>' var scope = $rootScope.$new(); scope.model = {name:'MyCtrl1'}; //alert(scope.model.name); var e3 = $compile(html)(scope); scope.$apply(); $('#container').append(e3[0]); }); 

Fiddle

scope.$apply() , but I'm not sure why. Hope someone else can explain this to us.

+5
source

All Articles