如何在没有 2 路绑定的情况下将 ngModel 传递给 AngularJS 组件? [英] How to pass ngModel to AngularJS component without 2-way binding?

查看:20
本文介绍了如何在没有 2 路绑定的情况下将 ngModel 传递给 AngularJS 组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 自定义输入作为 AngularJS 1.5 组件 使用单向数据绑定和 ngModel 作为双向数据绑定:

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,
   }

在文件 actTextField.js 中提供的 Plunk.我想关注 新的 Angular 1.x ES2015 风格指南,通往 Angular 2 的路径 Todd 写道:

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

因此,ngModel 的 2-way 数据绑定可能不是一个好的选择,它应该是 1-way.另一方面,我想让组件尽可能简单 - 例如,没有 on-change 回调.它应该与带有 ngModel 指令的原生 input 接近.是否可以将 ngModel 传递给没有 2 路数据绑定的组件,同时能够从组件更改其值,以避免(例如)额外的回调?预先感谢您的每一个回答.

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.

推荐答案

如果您打算使用 angular 组件,请尝试明智地使用一种方式绑定.在他的视图模型中托管模型的上层父级应该是唯一能够修改它的人.如果你想让子组件修改模型,你需要这样传递一个函数:

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.

这篇关于如何在没有 2 路绑定的情况下将 ngModel 传递给 AngularJS 组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆