我正在研究使用Angular 2的UpgradeAdapter来转换我的库。我的许多指令使用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">
但是,当我使用myTextbox
升级upgradeAdapter.upgradeNg1Component('myTextbox')
时,正如预期的那样我获得Error: Can not locate 'ngModel'
答案 0 :(得分:2)
我一直试图自己解决这个问题,答案并不简单。您可以在https://github.com/angular/angular/issues/8314#issuecomment-229391970。
处进行此操作一种解决方法是在ng1组件上创建一个ng1包装器,然后对包装器进行ngupgrade。这个包装器不会使用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-model =&#34; model&#34;
然后在您的ng2组件中,您可以使用香蕉 [()]。但同样我不确定它将如何正确使用表单控件。如果你想出更多,请告诉我。