-1

Having an input with ngModel which has $formatters and $parsers -

link: function(scope, element, attrs, ngModel) {
    //format text going to user (model to view)
    ngModel.$formatters.push(function(obj) {
        return obj.first;
    });
}

After I make any change in the input , I miss this model on the scope , mean - {{person.first}} display nothing .

Here is the full code -

var myAppModule = angular.module('myApp', []); 
     myAppModule.controller('myCtrl',function ($scope) {
      $scope.person = {
    first: 'Alice',
    last: 'Bob'
   }
     })
  .directive('myDrtv',function(){
   return {
    restrict: 'A', 
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
     var _ngModel = ngModel;
     //format text going to user (model to view)
        ngModel.$formatters.push(function(obj) {
      return obj.first;
     });
     //format text from the user (view to model)
     ngModel.$parsers.push(function(value) {
      return value;
        });
    }
        
   }
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

 <div ng-app="myApp">
  <div ng-controller="myCtrl">
   Name : <input my-drtv  ng-model="person" type="text"><br>
   {{person.first}}
     </div>
  
 </div>

How could I change the input and still see it in {{person.first}} ?

Please don't answer me change it to ng-model="person.first" I looking solution with - ng-model="person"

URL87
  • 10,667
  • 35
  • 107
  • 174

1 Answers1

1

Change your input to the following:

<input my-drtv ng-model="person.first" type="text">

They way you have it, you are clobbering person and changing it from an object to a string.

Edit: If you want to keep first name and last name separate, then do something like this:

<input my-drtv ng-model="fullname" type="text">

and then in link, watch for changes and update person:

scope.$watch('fullname', function(nv) {
  person.first = extractFirstName(nv);
  person.last = extractLastName(nv);
});

(I left it to you to supply the extract functions).

Michael Hays
  • 6,878
  • 2
  • 21
  • 17