Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access ngModelController in Angular1.5 components?

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?

like image 752
Kyle Xie Avatar asked Aug 10 '16 01:08

Kyle Xie


1 Answers

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);
like image 118
naftalip Avatar answered Nov 06 '22 03:11

naftalip