NgModelController $ modelValue is empty when the directive is run

I have an attribute directive that I use for the input = text tag like this:

<input type="text" ng-model="helo" my-directive /> 

      

In my directive, I am trying to use ngModelController to store the initial value of my input, in this case the value of its associated ng model.

The directive is as follows:

app.directive('myDirective', function () {
   return {
            restrict: "A",
            scope: {

            },
            require: "ngModel",
            link: function (scope, elm, attr, ngModel) {
              console.log("hi");
              console.log(ngModel.$modelValue);
              console.log(ngModel.$viewValue);
              console.log(elm.val());
            }
   }
});

      

The problem is that ngModel. $ modelValue is empty, possibly because at the time the directive was initialized, the ngModel was not yet updated with the correct value. So how can I store in my directive the first value that is set in my input field?

How to correctly access ngModel. $ modelValue so that it has the correct value?

I also thank you for explaining why this doesn't work as I don't understand it while reading the docs.

Plunkr full example: http://plnkr.co/edit/QgRieF

+3


source to share


1 answer


Use $watch

in myDirective

 app.directive('myDirective', function () {
    return {
        restrict: "A",
        scope: {

        },
        require: "ngModel",
        link: function (scope, elm, attr, ngModel) {

          var mywatch = scope.$watch(function(){
            return ngModel.$viewValue;
          }, function(value){
            if(value){
              console.log("hi");
              console.log(ngModel.$modelValue);
              console.log(ngModel.$viewValue);
              console.log(elm.val());
              mywatch(); 
            } 
          });

        }
     }
 });

      



For a demo See this link

+3


source







All Articles