Skip to content

Instantly share code, notes, and snippets.

@NV
Last active May 18, 2021 09:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save NV/5291cc85b1f04e4be988 to your computer and use it in GitHub Desktop.
Save NV/5291cc85b1f04e4be988 to your computer and use it in GitHub Desktop.
Angular.js temperature converter sample app http://bl.ocks.org/NV/5291cc85b1f04e4be988
var app = angular.module('converter', []);
app.controller('MainController', function($scope) {
$scope.a = 0;
});
app.directive('converter', function(converters) {
return {
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
var converter = converters[attr.converter];
ngModel.$formatters.unshift(converter.formatter);
ngModel.$parsers.push(converter.parser);
},
controller: function($scope, $element) {
}
};
});
app.service('converters', function() { return {
c2f: {
formatter: function(c) {
return 9 / 5 * parseFloat(c) + 32;
},
parser: function(f) {
return 5 / 9 * (f - 32);
}
}
}});
<html ng-app="converter">
<head>
<meta charset="utf-8">
<title>Temperature Converter</title>
<script src="https://code.angularjs.org/1.2.16/angular.js"></script>
<script src="converter.js"></script>
</head>
<body ng-controller="MainController">
<div>
<input type="number" ng-model="a">℃ ⟷
<input type="number" ng-model="a" converter="c2f">℉
</div>
</body>
</html>
@NomanMasood0
Copy link

it's not a proper solution of converter

@NV
Copy link
Author

NV commented May 18, 2021

I'm not sure what doesn't work. Note that this code is from 2014.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment