ng-model 和 value 组合不适用于输入文本框 [英] ng-model and value combination not working for input text box

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

问题描述

我有两个输入文本框.我需要组合在两个文本框中输入的值并将其显示在第三个文本框中.如果我只使用第三个文本框中的 value,我就可以显示它.

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:框 1+框 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 ??

推荐答案

这是一个很好的问题,因为它说明了不正确的在 Angular 中思考"是如何导致问题的.

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

使用 Angular,您首先从模型开始.然后 View 绑定到模型并反映它 - 而不是相反.我的意思是 ng-value 不会设置模型,尽管它会改变视图.您(或者更确切地说,控制器)负责设置模型.

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.fullCode 等于 entity.nameentity.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.nameentity.code 更改时随时设置它,那么您可以使用 $watch:

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.fullCode 绑定到另一个输入,更改该输入将更改 entity.fullCode 并且不会使其等于 + 前两个.

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-model 和 value 组合不适用于输入文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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