<?php 
ob_start();
?>
<div>
	<div style="display: flex;flex-wrap: wrap;">
		<input type="{{mode=='edit'?'number':'text'}}" style="flex:1;text-align:right;border: none;width: 100%;outline: none;background: transparent;" ng-model="val" ng-change="changeed()" ng-blur="onblur()" ng-focus="onfocus($event)">
	</div>
</div>
<?php
$code=ob_get_clean();
?>
<script>
	app.directive('number', [function () {
		return {
			restrict: 'E',
			template : <?= json_encode($code) ?>,
			scope : {ngModel:"=?",format:"@?",ngChange:"&?"},
			controller : function($scope){
				$scope.val = "";
				$scope.mode = "";
				$scope.changeed = function(){
					$scope.ngModel = $scope.val * 1;
					setTimeout(function(){
						if($scope.ngChange){
							$scope.ngChange();
							$scope.$apply();
						}
					},50);
				};
				function acceptFormat(){
					setTimeout(function(){
						switch($scope.format){
							case "prix":
							case "Prix":
							case "PRIX":
								$scope.val = $scope.ngModel.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')+"0"; 
							break;
							default:
								$scope.val = $scope.ngModel;
							break;
						}
						$scope.$apply();
					},50);
				}
				$scope.onblur = function(){
					acceptFormat();
					if($scope.ngChange) $scope.ngChange();
					$scope.mode = "";
				};
				$scope.onfocus = function(e){
					$scope.val = $scope.ngModel; 
					$scope.mode = "edit";
					setTimeout(function(){
						e.currentTarget.select();
					},50);
				};
				$scope.$watch("ngModel",function(){
					if($scope.mode == "edit") return;
					try{
						acceptFormat();
					}catch(e){
						$scope.val = "";
					}
				});
			},
			link: function (scope, iElement, iAttrs) {
				
			}
		};
	}]);
</script>