2016-04-27 99 views
2

我正在研究使用Angular 2的UpgradeAdapter来转换我的库。我的许多指令都使用ngModel与消费者进行通信,但在文档或代码中没有看到支持升级此类组件的任何内容。升级适配器是否支持ngModel?

有没有办法升级使用ngModel的Angular 1指令?

举例来说,我有一个指令:

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); 
     }); 
    } 
    }; 
}); 

在我的角度了1个应用我做消耗它:

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

然而,当我使用upgradeAdapter.upgradeNg1Component('myTextbox')升级myTextbox,预期我得到一个Error: Can not locate 'ngModel'

+0

你真的有两个不同的问题在这里。首先,UpgradeAdapter同时运行v1.X和v2。所以是的,它支持任何版本的任何运行。它实际上并没有为你升级任何东西。至于升级一个指令,看起来你只需要将它转换成一个组件指令。但是这是你要做的。 –

+0

@MthethewGreen我明白所有这些,但是我的问题是关于ngModel的。在Angular 1中ngModel是一个属性指令,它看起来不可升级。但是,由于ngModel是这样一个核心指令,我希望在升级指令时支持它。 – fenduru

+0

那看起来不像上面那样的问题。如果你用更多的信息更新你的问题,你可能会更好地帮助你。也许是你有什么样的例子,以及你如何尝试升级它。对于它的价值,[我没有看到ngModel无法使用](https://angular.io/docs/ts/latest/api/common/NgModel-directive.html)。 –

回答

0

我一直试图弄清楚自己和回答r不直截了当。你可以在https://github.com/angular/angular/issues/8314#issuecomment-229391970处跟进。

解决办法之一是通过ng1组件创建一个ng1包装,然后升级包装器。这个包装器不会使用ngModel,它只是简单地将所有参数传递给原始的ng1指令,而不做其他事情。

例如:

N1指令:

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) { 
     }};}); 

和包装:

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') 

重要的是要注意的是NG-模型= “模式”

然后在你的ng2组件中,你可以使用香蕉 [()]。但是,我不确定它将如何正确使用窗体控件。让我知道你是否了解更多。