cyberwombat
cyberwombat

Reputation: 40133

Adding properties to Angular directive controller (e.g. FormController)

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.

Upvotes: 1

Views: 78

Answers (1)

hon2a
hon2a

Reputation: 7214

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.

Upvotes: 2

Related Questions