Last active
November 23, 2015 16:33
-
-
Save bradberger/0c2acd80c9acba4a99fd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module('chargeback', ['ui.router', 'upload', 'ngAnimate']) | |
// Lots of code before the directive... | |
.directive('test', ['$filter', function($filter){ | |
// This should handle and input and return 0 or a valid float. | |
function toFloat(val){ | |
var f = parseFloat(val || 0) | |
return isFinite(f) ? f : 0; | |
} | |
// This actually uses the standard Angular filter directive to | |
// do that, calling it directly from JS instead of via the DOM. | |
// It's equivalent to this in HTML: | |
// {{ val | number:2 }} | |
function numberFormat(val){ | |
return $filter("number")(val, 2); | |
} | |
return { | |
require: 'ngModel', | |
restrict: 'A', | |
link: function($scope, elem, attrs, ngModel){ | |
// $formatters read from model value and pass to DOM for | |
// display. This ensures that the DOM always displays a "0.00" | |
ngModel.$formatters.push(numberFormat); | |
// $parsers read from the DOM and pass to validator, so | |
// need to convert to a float here if need a float in the | |
// ngModel value. If you don't need that, then can remove. | |
// In this case, we use it so that the $formatter function | |
// will always get a number. | |
ngModel.$parsers.push(toFloat); | |
} | |
}; | |
}]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment