eventos data angularjs click

data - Acción Angularjs al hacer clic en el botón.



ng click angular 4 (1)

Estoy tratando de hacer un cálculo, pero se está haciendo tan pronto como ingrese la cantidad. Solo quiero que esto suceda haciendo clic en un botón en lugar de hacerlo automáticamente.

Lo que he hecho hasta ahora:

<!DOCTYPE html> <html ng-app="myAppModule"> <head> <title>Angular JS - programming-free.com</title> <link href="https://dl.dropbox.com/u/96099766/DetailModalExample/bootstrap.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="lib/angularjs.min.js"></script> </head> <body> <div ng-controller="myAppController" style="text-align:center"> <p style="font-size:28px;"> Enter Quantity: <input type="text" ng-model="quantity"/> </p> <h2>Total Cost: Rs.{{calculateval(quantity,10)}}</h2> </div> <script type="text/javascript"> var myAppModule = angular.module(''myAppModule'', []); myAppModule.controller(''myAppController'', function($scope,calculateService) { $scope.quantity=1; $scope.calculateval = function(xval,yval) { return calculateService.calculate(xval,yval); } }); // Service myAppModule.factory(''calculateService'', function(){ return { calculate: function(xval,yval){ return xval*yval; } } }); </script> </body> </html>


El cálculo se produce inmediatamente, ya que la llamada de cálculo está vinculada en la plantilla, que muestra su resultado cuando cambia la quantity .

En su lugar, podría intentar el siguiente enfoque. Cambie su marca a la siguiente:

<div ng-controller="myAppController" style="text-align:center"> <p style="font-size:28px;">Enter Quantity: <input type="text" ng-model="quantity"/> </p> <button ng-click="calculateQuantity()">Calculate</button> <h2>Total Cost: Rs.{{quantityResult}}</h2> </div>

A continuación, actualice su controlador:

myAppModule.controller(''myAppController'', function($scope,calculateService) { $scope.quantity=1; $scope.quantityResult = 0; $scope.calculateQuantity = function() { $scope.quantityResult = calculateService.calculate($scope.quantity, 10); }; });

Aquí hay un ejemplo de JSBin que demuestra el enfoque anterior.

El problema con este enfoque es que el resultado calculado permanece visible con el valor anterior hasta que se hace clic en el botón. Para solucionar esto, puede ocultar el resultado cada vez que cambie la quantity .

Esto implicaría actualizar la plantilla para agregar un ng-change en la entrada, y un ng-if en el resultado:

<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>

y

<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>

En el controlador agregar:

$scope.showQuantityResult = false; $scope.calculateQuantity = function() { $scope.quantityResult = calculateService.calculate($scope.quantity, 10); $scope.showQuantityResult = true; }; $scope.hideQuantityResult = function() { $scope.showQuantityResult = false; };

Estas actualizaciones se pueden ver en esta demostración de JSBin .