A.S.F Studio A.S.F Studio - 4 months ago 10
Javascript Question

Angular bind from the controller to the input field

I have the following JSfiddle example.

HTML

<div ng-app="app" ng-controller="Example">
<input type="number" ng-model="data.mainOdd1" placeholder="#1 Main Odd" onfocus="this.placeholder=''" min="0" step="any" ui-blur="testfn('mainOdd1', $event, '#1 Main Odd');">
</div>


Javascript

angular
.module('app', [])
.directive('uiBlur', function($parse) {
return function(scope, elem, attrs) {
elem.bind('blur', function(event) {
scope.$apply(function() {
$parse(attrs.uiBlur)(scope, {
$event: event
});
});
});
};
})
.controller('Example', function($scope) {
$scope.data = {
'mainOdd1' : '',
};

$scope.testfn = function(propertyName, $event, placeHolder) {
debugger;
if (($event.target.validity.valid == false) ||
($scope.data[propertyName] == ''))
{
$scope.data[propertyName] = '';
$event.target.placeholder = placeHolder;
return;
}
debugger;
$scope.data[propertyName] = $scope.data[propertyName].toFixed(2);
};
});


I try to keep only two decimals.

I see two issues, the first one is that the number in the view does not change, although mainOdd1 does change. and the second one is that I get an error in the console about using the toFixed function.

What am I doing wrong here?

Thanks

Answer

Hi toFixed Error happening because of while converting toFIxed it will become String but your input type in number so it wont accept so u have to change to float

 $scope.testfn = function(propertyName, $event, placeHolder) {
      debugger;
      if (($event.target.validity.valid == false) ||
            ($scope.data[propertyName] == ''))
      {
        $scope.data[propertyName] = '';
        $event.target.placeholder = placeHolder;
        return;        
      }
      debugger;    
      $scope.data[propertyName] = parseFloat($scope.data[propertyName].toFixed(2));
    };
Comments