Instantly share code, notes, and snippets.

@NV /converter.js
Last active May 18, 2016

Embed
What would you like to do?
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="//code.angularjs.org/1.2.16/angular.js"></script>
<script src="app.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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment