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.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With