NG-模式和价值组合不工作的输入文本框 [英] ng-model and value combination not working for input text box

查看:104
本文介绍了NG-模式和价值组合不工作的输入文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个输入文本框。
我需要在两个文本框的输入值相结合,并在第三显示它。
我可以,如果我只使用了在第三个文本框来显示它。

I'm having two input text box. I need to combine the values entered in two text boxes and display it in the third. I'm able to display it if I use only the value in the third text box.

专栏1:

 <input type="text" ng-model="entity.name">

专栏2:

 <input type="text" ng-model="entity.code">

专栏3:BOX1 +盒2

Box 3:Box1+Box 2

  <input type="text" value="{{entity.name+ ' + ' + entity.code}}">

但是,如果我在第三个框中使用型号名称,逻辑似乎并不奏效:

However if I use a model name in the third box, the logic doesn't seem to be working:

 <input type="text" value="{{entity.name+ ' + ' + entity.code}}" 
        ng-model="entity.fullCode">

任何人都可以提出一个修正?

Can anyone suggest a fix ??

推荐答案

这是一个很好的问题,因为它说明了不正确的思维角度可能导致的问题。

This is a good question as it illustrates how incorrect "thinking in Angular" can lead to issues.

通过角开始与模型第一。然后在视图是绑定到模型,反映它 - 而不是其他方式。我的意思是在这个 NG-值将不设置模式,虽然它会改变看法。您(或者更确切地说,控制器)负责设置模式。

With Angular you start with model first. Then the View is bound to the model and reflects it - not the other way around. What I mean by that is that ng-value would not set the model, although it would alter the view. You (or rather, the controller) is responsible for setting the model.

所以,如果你需要 entity.full code 等于 entity.name 的串联和实体。code ,那么你应该在控制器中进行设置。

So, if you need entity.fullCode to equal the concatenation of entity.name and entity.code, then you should set it in the controller.

例如,如果你想设置的任何时间 entity.name 实体。code 变化,那么你可以这样写 $观看

For example, if you wanted to set it any time entity.name or entity.code change, then you could do so with $watch:

$scope.$watch("entity.name + entity.code", function(newVal){
   $scope.entity.fullCode = $scope.entity.name + "+" + $scope.entity.code;
})

请注意,虽然,因为你是结合 entity.full code 另一种输入,改变该输入会改变 entity.full code ,也不会使它等于 + 前两个。

Note, though, that since you are binding entity.fullCode to another input, changing that input would change entity.fullCode and would not make it equal to the + of the first two.

这篇关于NG-模式和价值组合不工作的输入文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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