Skip to content

Instantly share code, notes, and snippets.

Last active Aug 29, 2015
What would you like to do?
Angular Sample - Calculating Amount with Quantity and Price
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8" />
<title>Angular Sample</title>
<body ng-app="myApp">
<div ng-controller="myController">
<label>Quantity:</label><br />
<input type="number" ng-model="quantity" />
<label>Price:</label><br />
<input type="number" ng-model="price" />
<label>Amount:</label><br />
<input type="number" ng-model="amount" />
<!--Description in English-->
<li>If the quantity and the price fields are filled, the amount field will be calculated automatically.</li>
<li>If the price field isn't filled, you can fill the amount field by hand freely.</li>
<!--Description in Japnaese (日本語解説)-->
<script src=""></script>
<script src="MyScripts/myScript.js"></script>
interface myScope extends ng.IScope {
quantity: number; // Japanese:数量
price: number; // Japanese:単価
amount: number; // Japanese:金額
module myModule {
angular.module("myApp", [])
.controller("myController", ['$scope', ($scope: myScope) => {
$scope.quantity = null;
$scope.price = null;
$scope.amount = null;
// EN:This is a ko.computed(KnockoutJS) like approach that I think.
// JP:Angularでko.computed(KnockoutJS)みたいなことをやってみました。
$scope.$watch(() => [$scope.quantity, $scope.price], // EN:Observing two variables./JP:数量と単価の変更を監視する。
(newVal: number[], oldVal: number[]) => {
var newQuantity: number = newVal[0],
newPrice: number = newVal[1],
oldQuantity: number = oldVal[0],
oldPrice: number = oldVal[1];
if (newQuantity && newPrice) { // EN:If newVals are calculable, the amount will be updated./JP:数量と単価が有効値なら金額を自動計算する。
$scope.amount = newQuantity * newPrice;
if (!newPrice && oldPrice) { // EN:If the price changed from calculable to not, the amount will be init./JP:単価が有効値から無効値に変化したら金額をリセットする。
$scope.amount = null;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment