问题
I have custom input as AngularJS 1.5 component with one-way data bindings and ngModel as two-way data binding:
return {
bindings: {
form: "<",
fieldName: "@",
minLength: "@",
maxLength: "@",
isRequired: "@",
errors: "<",
value: "=ngModel"
},
templateUrl: "actTextField.html",
controller: ActTextFieldController,
}
in file actTextField.js
in provided Plunk. I want to follow A new Angular 1.x ES2015 styleguide, the path to Angular 2 where Todd wrote:
We no longer should utilise two-way data-binding through '=' syntax for bindings
Use one-way databinding '<' and functions '&'
So, 2-way data binding for ngModel
may not be a good choice, it should be 1-way. On the other hand, I want to keep component as simple as possible - without, for example, on-change
callback. It should act close to native input
with ngModel
directive. Is it possible to pass ngModel
to component without 2-way data binding and at the same time be able to change its value from a component, to avoid (for example) additional callbacks? Thank you in advance for every answer.
回答1:
If you plan on using angular component, try use one way binding wisely. The upper parent hosting the model in his viewmodel should be the only one to be able to modify it. if you want the child component to modify the model, you need to pass along a function this way:
bindings: {
updateUsername : '&', // Function
user : '<' // Model
}
They did it this way to simplify angular concept and to reduce the number of events on the page using directives.
来源:https://stackoverflow.com/questions/38953377/how-to-pass-ngmodel-to-angularjs-component-without-2-way-binding