Search code examples
javascriptangularjsextendingangular-decorator

Angular extend vs $provide.decorator


I am confused. Could you clarify the difference among angular.extend() and $provide.decorator? Why and when use the second one? Is decorator doing something different than extend? I cannot find any answer after having performed a search...


Solution

  • angular.extend() is just yet another implementation of the standard JavaScript extend tool. You can find many other similar (when not identical) implementations, like Object.assign(), jQuery's, Underscore's...

    $provide.decorator() though is the Angular implementation of the decorator pattern, and is much more powerful as it allows you to change the behavior of a provider transparently, i.e. without having to modify the dependent objects. The example in the doc is quite straightforward: each time $log.warn() is called, the message will be automatically prefixed by 'Decorated Warn: '.