Angular decorate

10,239 views

Published on

Use AngularJS' decorate function with ease

Published in: Software

Angular decorate

  1. 1. $PROVIDE .DECORATOR() MODIFYING THE BEHAVIOR OF ANGULARJS' CORE SERVICES
  2. 2. DAMIEN KLINNERT Software Engineer at Small-Improvements damienklinnert.com twitter.com/damienklinnert github.com/damienklinnert
  3. 3. THE DECORATOR PATTERN
  4. 4. THE COMPLEX WAY angular.module(moduleName, []) .config(function ($provide) { $provide.decorator(serviceName, function ($delegate) { // modify behavior here return $delegate; }); });
  5. 5. THE SIMPLE WAY angular.module(moduleName, []) .decorate(serviceName, function ($delegate) { // modify behavior here return $delegate; }); www.github.com/damienklinnert/angular-decorate
  6. 6. ONE APPEND FILE EXTENSION IN $TEMPLATECACHE.GET()
  7. 7. What you have is: <div ng-include="'views/custom-template.html'"></div> What you want is: <div ng-include="'views/custom-template'"></div>
  8. 8. // Decorator definition angular.module('$templateCache+get', ['ng']) .decorate('$templateCache', function ($delegate) { var _get = $delegate.get; $delegate.get = function (key) { return _get.call(_get, key + ".html"); }; return $delegate; }); // Use decorator in whole app angular.module('app', ['$templateCache+get', ...])
  9. 9. TWO ADD BASEURL TO EACH $RESOURCE
  10. 10. Make this possible: var users = $resource('http://localhost/users'); console.log(users.baseUrl); // this is new
  11. 11. // Decorator definition angular.module("$resource+baseUrl", ['ngResource']) .decorate('$resource', function ($delegate) { return function (baseUrl) { var ret = $delegate.apply(this, arguments); ret.baseUrl = baseUrl; return ret; }; }); // Use decorator in whole app angular.module('app', ['$resource+baseUrl', ...])
  12. 12. THREEINSTRUMENT ANGULAR PERFORMANCE
  13. 13. What can you do with this? angular.module('$rootScope+instrument', []).decorate('$rootScope', function ($delegate) { $delegate.__proto__.$watch = function () { ... }; $delegate.__proto__.$apply = function () { ... }; return $delegate; });
  14. 14. THANK YOU RELATED MATERIAL angular-decorate www.github.com/damienklinnert/angular-decorate Hacking Core Directives in AngularJS http://briantford.com/blog/angular-hacking-core.html Angular $provide http://docs.angularjs.org/api/auto/object/$provide

×