Campo de entrada de actualización de Angular JS después del cambio
-
12-12-2019 - |
Pregunta
Estoy intentando crear una calculadora sencilla en Angular en la que puedo anular el total si quiero.Tengo esta parte funcionando, pero cuando vuelvo a ingresar un número en los campos uno o dos, el total no se actualiza en el campo.
Aquí está mi jsfiddle http://jsfiddle.net/YUza7/2/
La forma
<div ng-app>
<h2>Calculate</h2>
<div ng-controller="TodoCtrl">
<form>
<li>Number 1: <input type="text" ng-model="one">
<li>Number 2: <input type="text" ng-model="two">
<li>Total <input type="text" value="{{total()}}">
{{total()}}
</form>
</div>
</div>
el javascript
function TodoCtrl($scope) {
$scope.total = function(){
return $scope.one * $scope.two;
};
}
Solución
Puede agregar la directiva de ng-change
a los campos de entrada.Eche un vistazo a los docs ejemplo .
Otros consejos
Supongo que cuando ingresas un valor en el campo de totales, esa expresión de valor de alguna manera se sobrescribe.
Sin embargo, puede adoptar un enfoque alternativo:Cree un campo para el valor total y cuando one
o two
los cambios actualizan ese campo.
<li>Total <input type="text" ng-model="total">{{total}}</li>
Y cambia el javascript:
function TodoCtrl($scope) {
$scope.$watch('one * two', function (value) {
$scope.total = value;
});
}
Ejemplo de violín aquí.
Escribí una directiva que puede usar para unir un modelo NG a cualquier expresión que desee.Siempre que cambie la expresión, el modelo está configurado en el nuevo valor.
module.directive('boundModel', function() {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ngModel) {
var boundModel$watcher = scope.$watch(attrs.boundModel, function(newValue, oldValue) {
if(newValue != oldValue) {
ngModel.$setViewValue(newValue);
ngModel.$render();
}
});
// When $destroy is fired stop watching the change.
// If you don't, and you come back on your state
// you'll have two watcher watching the same properties
scope.$on('$destroy', function() {
boundModel$watcher();
});
}
});
Puede usarlo en sus plantillas como esta:
<li>Total<input type="text" ng-model="total" bound-model="one * two"></li>
Solo necesita corregir el formato de su HTML
<form>
<li>Number 1: <input type="text" ng-model="one"/> </li>
<li>Number 2: <input type="text" ng-model="two"/> </li>
<li>Total <input type="text" value="{{total()}}"/> </li>
{{total()}}
</form>
Crear una directiva y poner un reloj en él.
app.directive("myApp", function(){
link:function(scope){
function:getTotal(){
..do your maths here
}
scope.$watch('one', getTotals());
scope.$watch('two', getTotals());
}
})