Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the upgrade adapter support ngModel?

I'm looking into using Angular 2's UpgradeAdapter in order to transition my library. Many of my directives use ngModel to communicate with the consumer, but I do not see anything in the documentation or code to support upgrading this kind of component.

Is there a way to upgrade an Angular 1 directive that uses ngModel?

For instance, I have a directive:

module.directive('myTextbox', function() {
  return {
    template: '<input type="text"></input>',
    scope: {},
    bindToController: true,
    controllerAs: 'ctrl',
    require: 'ngModel',
    link: function(scope, elem, attrs, ngModel) {
      ngModel.$render = function() {
        elem.find('input').val(ngModel.$viewValue);
      }

      elem.find('input').on('change', function(e) {
        ngModel.$setViewValue(e.target.value);
      });
    }
  };
});

in my angular 1 app I consume it by doing:

<my-textbox ng-model="textboxValue">

However when I upgrade myTextbox using upgradeAdapter.upgradeNg1Component('myTextbox'), as expected I get an Error: Can not locate 'ngModel'

like image 933
fenduru Avatar asked Oct 30 '22 04:10

fenduru


1 Answers

I have been trying to figure this out myself and the answer isn't straightforward. You can follow this up at https://github.com/angular/angular/issues/8314#issuecomment-229391970.

One work-around is to create a ng1 wrapper over the ng1 component and then ngupgrade the wrapper. This wrapper will not use ngModel, it just simply pass all parameters to the original ng1 directive, without doing other things.

For Example:

n1 directive:

 angular.module('components')
  .directive('checkboxes', function () {
      return {
        'require': 'ngModel',
        'restrict': 'E',
        'scope': {
          'model': '=ngModel',
          'name': '=?',
          'options': '=',
          'settings': '=?'
        },
        'templateUrl': 'app/components/forms/checkboxes/checkboxes.html',
        'controller': function ($scope) {
      }};});

And the wrapper:

  angular.module('components')
      .directive('checkboxesWrapper', function () {
          return {
            'restrict': 'E',
            'scope': {
              'model': '=',
              'name': '=?',
              'options': '=',
              'settings': '=?'
            },
            'template': '<checkboxes ng-model="model" name="name" options="options" settings="settings"></checkboxes>',
            'controller': function ($scope) {
          }};});

UpgradeAdapter.upgradeNg1Component('checkboxesWrapper')

The important thing to note is ng-model="model"

Then in your ng2 component you can use the banana [()]. But again i am not sure how correctly it will work with form-controls. Let me know if you figure out more.

like image 181
jin Avatar answered Nov 08 '22 05:11

jin