Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 986
Premier Avatar asked Mar 21 '13 22:03

Premier


People also ask

What is isolated scope in AngularJS?

Isolated scope directive is a scope that does not inherit from the parent and exist on its own. Scenario: Lets create a very simple directive which will show the object from the parent controller.

Does Ng include create a new scope?

In this case, where you need to load templates from other domains or other protocols, then you can add them to your trusted resource URL list, which will set the url as a trusted url in your application. The ng-include directive is executed at priority level -400 and creates new scope every time it is invoked.

What does $compile do in AngularJS?

Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.


2 Answers

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

like image 98
Alex Osborn Avatar answered Sep 21 '22 15:09

Alex Osborn


If you only need to interpolate things, use the $interpolate service instead of $compile, and then you won't need a scope:

myApp.factory('myService', function($interpolate) {     var template = "<h1>{{title}}</h1>";     var interpolateFn = $interpolate(template);     return {         open: function(title) {             var html = interpolateFn({ title: title });             console.log(html);             // append the html somewhere         }     } }); 

Test controller:

function MyCtrl($scope, myService) {     myService.open('The Title'); } 

Fiddle

like image 37
Mark Rajcok Avatar answered Sep 20 '22 15:09

Mark Rajcok