AngularJS - How can I create a new, isolated scope programmatically?

Premier picture Premier · Mar 21, 2013 · Viewed 54.6k times · Source

I want to create an AlertFactory with Angular.factory. I defined an html template like follow

var template = "<h1>{{title}}</h1>";

Title is provided by calling controller and applied as follow

var compiled = $compile(template)(scope);
body.append(compiled);

So, how I can pass isolated scope from controller to factory? I'm using in controller follow code

AlertFactory.open($scope);

But $scope is global controller scope variable. I just want pass a small scope for factory with just title property.

Thank you.

Answer

Alex Osborn picture Alex Osborn · Mar 22, 2013

You can create a new scope manually.

You can create a new scope from $rootScope if you inject it, or just from your controller scope - this shouldn't matter as you'll be making it isolated.

var alertScope = $scope.$new(true);
alertScope.title = 'Hello';

AlertFactory.open(alertScope);

The key here is passing true to $new, which accepts one parameter for isolate, which avoids inheriting scope from the parent.

More information can be found at: http://docs.angularjs.org/api/ng.$rootScope.Scope#$new