1

How can I globally extend the native Angular FormController with additional methods?

For example, I would like my forms to have an additional method setNew() (similar to already existing $setPristine(), etc). Right now I am doing this in each controller but I'd like it available throughout the app without declaring it all over the place.

hon2a
  • 7,006
  • 5
  • 41
  • 55
cyberwombat
  • 38,105
  • 35
  • 175
  • 251
  • What do you mean by native Angular FormController? Can you also give some explanation on the custom methods i.e what is their purpose? – Nexus23 Dec 14 '14 at 19:45
  • check this out: http://stackoverflow.com/questions/16539999/angular-extending-controller – Nexus23 Dec 14 '14 at 20:06
  • @Nexus23 I saw that but that is about creating a new controller from an existing one - not sure how I would modify the native controllers – cyberwombat Dec 14 '14 at 20:09
  • I guess it can be done by a decorator but the idea requires validation. – Gleb Vinnikov Dec 14 '14 at 20:28

1 Answers1

2

You can define additional behavior for directives by define other directives with the same name. Consequently, it seems you can do this:

angular.module('app', [])
  .directive('ngForm', formControllerDecorator)
  .directive('form', formControllerDecorator);

function formControllerDecorator () {
  return {
    require: 'form',
    link: function ($scope, $element, $attrs, formCtrl) {
      formCtrl.setNew = function () {
        // ...
      };
    }
  };
}

You need to declare two directives in this case, because ngForm is in fact an alias for form.

hon2a
  • 7,006
  • 5
  • 41
  • 55