How to access the $ngModelController from inside the Controller without a Form and without a Directive

All we need is an easy explanation of the problem, so here it is.

Maybe it’s a rookie mistake, but I can’t seem to access the $scope.model‘s $ngModelController so I can grab the $viewValue from it.

I have an input without a form (im using ui-mask directive):

<input type="text" ng-model="inicio" name="inicio" ui-mask="99/99/9999">
// inside my controller
$scope.inicio = dateFilter((new Date).getTime(), 'dd/MM/yyyy');

ui-mask set the $modelValue a different value than $viewValue, making it hard to send formatted data to the server. When the $scope.inicio model changes, the value is a date without slashes, like 01012014. So I need to be able to get the controller for that input, but without having to wrap it in a form, and have to use $scope.myForm.inicio.$viewValue. It MUST be possible…

Things I know I can do, but seems hacky, there must be a simpler way:

  • Put the element inside a form and access it through $scope.myForm.input.$viewValue
  • Get the element data using jQuery $('input[name="inicio"]').data('$ngModelController');
  • Get the element using angular.element('input[name="inicio"]').controller('ngModel');
  • Create a directive, put it in the input, and update my scope model with it
app.directive('viewValue', function(){
  return {
    priority: 10,
    require: 'ngModel',
    link: function(scope, element, attrs, controller){
      scope.$watch(attrs.viewValue, function(newValue, oldValue){
        if (newValue !== oldValue){
          scope[attrs.viewValue] = controller.$viewValue;
        }
      });
    }
  }
});
<input type="text" ui-mask="99/99/9999" ng-model="inicio" view-value="inicio">

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

I like the directive alternative. Essentially the ui-mask directive isn’t doing what you want, so you might as well write your own directive.

You shouldn’t have to pass inicio to your view-value directive. Instead, add your own parser to ngModelCtrl.$parsers. Here’s an example: https://stackoverflow.com/a/15556249/215945

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply