<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<p>Return an object from $provide.factory then assign it to a scope object in your link or controller function. This leads to far more readable directives and more maintainable code.</p>
<p>Static Factory returns a plain Object</p>
<class-directive></class-directive>
<class-directive></class-directive>
<hr>
<p>Dynamic factory returns an object with a constructor. You can also use an Angular service to provide you a "newed" object.</p>
<dynamic-directive name="Instance 1" change="Instance 1 changed"></dynamic-directive>
<dynamic-directive name="Instance 2" change="Instance 2 changed"></dynamic-directive>
JavaScript
angular.module("fiddle",[
"classFactory",
"dynamicFactory",
"classDirective",
"dynamicDirective"
]);
//return a plain object from a factory
angular.module("classFactory", [], function ($provide) {
$provide.factory("classFactory", function () {
return {
someProp: "Return objects from factories",
click: function(){
this.someProp = "Then assign them to $scope";
}
};
});
});
angular.module("classDirective", [])
.directive("classDirective", function (classFactory, $timeout) {
return {
restrict: "ACE",
template: "<button ng-click='co.click()'>" +
"{{co.someProp}}" +
"</button>",
link: function(scope, elm, attr, ctrl) {
scope.co = classFactory;
$timeout(function(){
// You can call methods and update properties on the factory
// object itself, provided it is wrapped in an apply call.
classFactory.someProp = "They are all the same object in this case";
}, 3000);
}
};
});
//return an instantiable object with a constructor
angular.module("dynamicFactory", [], function ($provide) {
$provide.factory("dynamicFactory", function () {
var dynamic = (function() {
function dynamic(someProp) {
this.someProp = someProp;
}
dynamic.prototype.click = function(v) {
this.someProp = v;
};
return dynamic;
})();
return dynamic;
});
});
//Use attributes to set properties on the new Object.
angular.module("dynamicDirective", [])
.directive("dynamicDirective", function (dynamicFactory, $timeout) {
return {
restrict: "ACE",
template: "<button ng-click='do.click(change)'>" +
"{{do.someProp}}" +
"</button>",
scope: {},
link: function(scope, elm, attr, ctrl) {
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.