ng-model and value combination not working for input text box

forgottofly picture forgottofly · Feb 5, 2015 · Viewed 15.3k times · Source

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.

Box 1:

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

Box 2:

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

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 ??

Answer

New Dev picture New Dev · Feb 5, 2015

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

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.

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

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;
})

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.