How to access ngModelController in Angular1.5 components?
Asked Answered
D

1

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?

Duluth answered 10/8, 2016 at 1:45 Comment(0)
I
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);
Intelligent answered 13/2, 2017 at 15:29 Comment(2)
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 ???Welltodo
I put a plunker here plnkr.co/edit/HCmqdowSX0nu0l0au7Ba?p=preview . works like a charm. u rock man !Welltodo

© 2022 - 2024 — McMap. All rights reserved.