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.
Followings are the steps:
var comiledHTML = angular.element(yourHTML);
var newScope = $rootScope.$new();
var linkFun = $compile(comiledHTML);
var finalTemplate = linkFun(newScope);
YourHTMLElemet.append(finalTemplate);
check out my plunkr. I'm programmatically generating a widget directive with a render directive.
https://plnkr.co/edit/5T642U9AiPr6fJthbVpD?p=preview
I assume when you are talking about an isolate scope you are talking about a directive.
Here is an example of how to do it. http://jsfiddle.net/rgaskill/PYhGb/
Basically, attach a controller to a directive that has defined an isolate scope. The scope injected into the directive controller will be an isolate scope. In the directive controller you can inject your AlertFactory with wich you can pass the isolate scope to.
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.The key here is passing
true
to$new
, which accepts one parameter forisolate
, which avoids inheriting scope from the parent.More information can be found at: http://docs.angularjs.org/api/ng.$rootScope.Scope#$new
If you only need to interpolate things, use the $interpolate service instead of $compile, and then you won't need a scope:
Test controller:
Fiddle