Extending AngularJs Directive

Kyle picture Kyle · Jun 9, 2013 · Viewed 49.8k times · Source

I'd like to make a minor modification to a 3rd party directive (specifically Angular UI Bootstrap). I simply want to add to the scope of the pane directive:

angular.module('ui.bootstrap.tabs', [])
.controller('TabsController', ['$scope', '$element', function($scope, $element) {
  // various methods
}])
.directive('tabs', function() {
  return {
    // etc...
  };
})
.directive('pane', ['$parse', function($parse) {
  return {
    require: '^tabs',
    restrict: 'EA',
    transclude: true,
    scope:{
      heading:'@',
      disabled:'@' // <- ADDED SCOPE PROPERTY HERE
    },
    link: function(scope, element, attrs, tabsCtrl) {
      // link function
    },
    templateUrl: 'template/tabs/pane.html',
    replace: true
  };
}]);

But I also want to keep Angular-Bootstrap up to date with Bower. As soon as I run bower update, I'll overwrite my changes.

So how do I go about extending this directive separately from this bower component?

Answer

Dan picture Dan · Jun 9, 2013

Probably the simplest way to solve this is to create a directive on your app with the same name as the third party directive. Both directives will run and you can specify their run order using the priority property (higher priority runs first).

The two directives will share scope and you can access and modify the scope of the third party directive via your directive's link method.

Option 2: You can also access a third party directive's scope by simply putting your own arbitrarily named directive on the same element with it (assuming neither directive uses isolate scope). All non-isolate scope directives on an element will share scope.

Further Reading: https://github.com/angular/angular.js/wiki/Dev-Guide%3A-Understanding-Directives

Note: My previous answer was for modifying a third party service, not a directive.