8

When I use angular.component() to create the brand new component that angular 1.5 provides, there's no link function, so the old way of injecting ngModelController or any other controllers doesn't work.

require: 'ngModel', link: function(scope, element, attrs, ctrls)

The above code is for a directive to access ngModelController. How do we access it in the component now?

Kyle Xie
  • 722
  • 1
  • 8
  • 28

1 Answers1

7

Instead of getting a ctrls array, you get them now by name, just like bindings use to:

class MyComponentController implements ng.IComponentController {

    public modelCtrl: ng.INgModelController;
    ...
    ...
    // use modelCtrl here
    // instead of ctrls[0]
    ...
    ...
}

const MyComponent: ng.IComponentOptions = {
    template: '...',
    bindings: {...},
    require: {modelCtrl: 'ngModel'},
    controller: MyComponentController
}

angular.module('myModule').component('MyComponent', MyComponent);

Or, if you prefer plain JS:

function MyComponentController() {
    ...
    ...
    // use this.modelCtrl here
    ...
    ...
}

var MyComponent = {
    template: '...',
    bindings: {...},
    require: { modelCtrl: 'ngModel' },
    controller: MyComponentController
};

angular.module('myModule').component('MyComponent', MyComponent);
naftalip
  • 133
  • 2
  • 7
  • So I tried this with 1.5.8 and getting access to $pristine, $valid etc. is not possible eg. this.modelCtrl.$pristine is not accessible and an error is thrown that pristine is not accessible on undefined. Can u plz show how we can access $pristine, $valid, $$formatters etc. Using this.modelCtrl ??? – Plankton Jul 11 '17 at 11:57
  • I put a plunker here http://plnkr.co/edit/HCmqdowSX0nu0l0au7Ba?p=preview . works like a charm. u rock man ! – Plankton Jul 13 '17 at 07:00