JSFiddle - React, Tailwind, and code Playground

by paperelectron

HTML

<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) {
  ...