Custom string to integer directive, no value in post

27 views
Skip to first unread message

Prashant

unread,
Jul 14, 2017, 11:26:07 PM7/14/17
to Angular and AngularJS discussion
Hi,

AngularJS v1.6.4
Angular Material Design v1.1.0

I'm fairly to ng and getting my hands on slowly. Here is the situation:
1. Forms are dynamically loaded.
2. Once form is loaded data is fetched from server in json format.
3. Every this is string in data.
4. When you are passing value to ng-model on input(number) it should be a number which is not in my case.
5. To solve above situation I have written a directive.
angular.module('toInt', [])
.directive('toInt', function(){
 
return {
    restrict
: 'A',
   
require: 'ngModel',
    link
: function(scope, $element, attrs, ngModel) {
     
// view --> model (change integer to string)
      ngModel
.$parsers.push(function(viewValue){
       
if(viewValue)
         
return viewValue.toString();
       
else
         
return '';
     
});  
     
// model --> view (change string to integer)
      ngModel
.$formatters.push(function(modelValue){
       
return parseInt(modelValue);
     
});
   
}
 
};
});
This is working as expected. When I delete the number I get an error message because I'm using ng-messages and 'require' is set.
So far so good. When I submit the form with empty input(for testing my submit button is always enable), I'm not receiving this field and
my post is empty. I have node idea why it's happening. In $parsers I'm returning an empty string in case there is no viewValue but it's strange to me.
What I'm looking in case if empty field is sent to post I should receive an empty value or if there is a value it should go to post as string.

Cheers




Reply all
Reply to author
Forward
0 new messages