alehro
alehro

Reputation: 2208

$compile(html)(scope) ignores the scope I've 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 the behavior

As you can see it renders two 'MyCtrl' strings. I.e. angular ignores the scope object I've created manually.

The question is: How do I make $compile to use the scope I've created?


UPDATE: Ugly workaround:

After a call to $compile apply model one more time:

angular.element(e3[0]).scope().$apply(function(scope) {
    scope.model = {name:'MyCtrl1'};
});

Upvotes: 4

Views: 5213

Answers (1)

Mark Rajcok
Mark Rajcok

Reputation: 364677

ng-app creates an injector, then you are creating another one. This is probably not what you want. I moved most of your code into a run() method, which has the $compile service and $rootScope injected into it:

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() is needed, but I'm not sure why. Hopefully someone else can explain that to us.

Upvotes: 5

Related Questions