Search code examples
javascriptangularjsangular-decorator

AngularJS Decorators IE7


Related question: AngularJS Decorator without object.defineProperty

It seems the standard way to apply decorators is with object.defineProperty but that is not supported in IE7.

There are some polyfill options for object.defineProperty:

I have also done some experimenting in plunkr with some interesting results.

<div  ng-controller="ParentCtrl">
  <div ng-controller="ChildCtrl"></div>
</div>
<div ng-controller="SiblingCtrl"></div>

var app = angular.module('plunker', []);

app.config(['$provide', function($provide){
  $provide.decorator('$rootScope', ['$delegate', function($delegate){
    $delegate.a = 1;
    $delegate.constructor.prototype.b = 2;
    Object.defineProperty($delegate.constructor.prototype, 'c', {
      value: 3
    });
    return $delegate;
  }]);
}]);

app.controller('ParentCtrl', function($rootScope, $scope) {
  console.info('ParentCtrl', $rootScope.a); // 1
  console.info('ParentCtrl', $rootScope.b); // 2
  console.info('ParentCtrl', $rootScope.c); // 3
  console.info('ParentCtrl', $rootScope.constructor.prototype.a); // undefined
  console.info('ParentCtrl', $rootScope.constructor.prototype.b); // 2
  console.info('ParentCtrl', $rootScope.constructor.prototype.c); // 3
  $rootScope.a = 'a';
  $rootScope.b = 'b';
  $rootScope.c = 'c';
});

app.controller('ChildCtrl', function($rootScope, $scope) {
  console.info('ChildCtrl', $rootScope.a); // 1
  console.info('ChildCtrl', $rootScope.b); // b
  console.info('ChildCtrl', $rootScope.c); // 3
  console.info('ChildCtrl', $rootScope.constructor.prototype.a); // undefined
  console.info('ChildCtrl', $rootScope.constructor.prototype.b); // 2
  console.info('ChildCtrl', $rootScope.constructor.prototype.c); // 3
});

app.controller('SiblingCtrl', function($rootScope, $scope) {
  console.info('SiblingCtrl', $rootScope.a); // a
  console.info('SiblingCtrl', $rootScope.b); // b
  console.info('SiblingCtrl', $rootScope.c); // 3
  console.info('SiblingCtrl', $rootScope.constructor.prototype.a); // undefined
  console.info('SiblingCtrl', $rootScope.constructor.prototype.b); // 2
  console.info('SiblingCtrl', $rootScope.constructor.prototype.c); // 3
});

And my question is: Which is the right way to provide a method to rootScope like this answer shows.


Solution

  • I went with this

    app.config(['$provide', function($provide){
      $provide.decorator('$rootScope', ['$delegate', function($delegate){
        $delegate.func = function() {
           ...
        };
        return $delegate;
      }]);
    }]);
    

    This was the simplest solution and it works in IE7. Calls to constructor or prototype or __proto__ without or without polyfills just led to endless trouble.