Numberic field binding
Binding a numeric field to string values using a directive.
by tdjager
HTML
<script src="http://code.angularjs.org/1.2.4/angular.min.js"></script>
<div data-ng-controller="Ctrl">
<h2>With directive</h2>
<input data-ng-model="realnumber" numericbinding type="number"/>
<input data-ng-model="stringnumber" numericbinding type="number"/>
<h2>Without directive</h2>
<input data-ng-model="realnumber2" type="number"/>
<input data-ng-model="stringnumber2" type="number"/>
</div>
JavaScript
var myApp = angular.module('myApp', []);
myApp.directive('numericbinding', function () {
return {
restrict: 'A',
require: 'ngModel',
scope: {
model: '=ngModel',
},
link: function (scope, element, attrs, ngModelCtrl) {
if (scope.model && typeof scope.model == 'string') {
scope.model = parseInt(scope.model);
}
}
};
});
function Ctrl($scope) {
$scope.realnumber = 1;
$scope.stringnumber = "2";
$scope.realnumber2 = 1;
$scope.stringnumber2 = "2";
}