Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

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

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">
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...