Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs - Extending ngModel

Afternoon,

ngModelController gives you control over $dirty and $pristine but I would like to have my own one. How would I go about extending the ngModelController to offer something like ngModelCtrl.$setCustom()?

Cheers

like image 371
MaxWillmott Avatar asked Aug 05 '26 06:08

MaxWillmott


1 Answers

You cannot extend ngModelDirective, but what you can do is create your own ng-model. It's a relatively unknown thing in Angular that you can have multiple directives with the same name, and all of them will be executed. Here's a JSBin with an example: http://jsbin.com/nopoyiso/1/edit

And for those who can't be bothered opening the JSBin:

myApp.directive('ngModel', function() {
  return {
    restrict: 'A', 
    require: '?ngModel',
    link: function(scope, elem, attrs, ngModel) {
      ngModel.setCustom = function() {
        console.log('hello!');
      }
    }
  }
});

So this is a way to do it, but I think you'll end up confusing both yourself and others by doing this. Could you elaborate on what you're trying to do? Perhaps there's a better way to go about it.

like image 189
Anders Ekdahl Avatar answered Aug 06 '26 19:08

Anders Ekdahl