AngularJS Question

Set 'value' input with AngularJS function

I'm kinda noob with AngularJS I have the next div:

<div ng-app="" ng-controller="telController">

Teléfono: <input type="text" ng-model="telefono.numero" ><br>
<input type="text" ng-model="telefono.tras" >
<br>
El telefono es: {{telefono.telefonoCodificado()}}

</div>


The angularjs function is:

function telController($scope) {
$scope.telefono = {
numero: "",
telefonoCodificado: function() {
var x;
x = $scope.telefono;

var parte1;
parte1= $scope.telefono.numero;
var telCodificado = parte1.substring(0, 3)+"-"+parte1.substring(3, 6)+"-"+parte1.substring(6, 10);

return "A) "+x.numero+" <<>> "+ telCodificado;
},
tras : function(){
var y;
y = $scope.telefono.numero;
return y;
}
};
}


I want the input with ng-model='telefono.tras' get filled with the value that have been typing in the input ng-model="telefono.numero" but that doesn´t happend, what am I doing wrong?

Answer Source

New Answer:

After being updated on the issue, its better to use a ng-change to update the other variable.

JSFiddle Demo

Old Answer:

Hi There is no need to write a separate function to copy the ng-model (telefono.numero) to the variable telefono.tras, you can just assign the same variable. Like so.

JSFiddle Demo

Suppose you need telefono.tras populated for some function, then before calling the function, assign the telefono.numero value to telefono.tras.

So if you want to populate telefono.tras you can use the $watch() method to do this!

$scope.$watch('telefono.numero', function(newValue, oldValue){
    $scope.telefono.tras = newValue;
})

JSFiddle Demo

I hope this answer was useful, please let me know if there are any issues.

Suggestion: The input box is allowing numbers and text, to allow only numbers you need to add a directive, refer this link

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download