Search code examples
javascriptangularjsangularjs-directiveangular-ngmodelisolated-scope

how to get ng-model value in directive


I have written a directive in AngularJS, and used the input type number with min-max and ng-model attribute. I have used isolated scope. In the directive, I have written a blur event. I am getting min-max value but not getting ng-model value:

<input my-directive min="5" max="10" ng-model="num" type="number">
myApp.directive('myDirective', function () {
  function link($scope, ele, attr) {
    $scope.$watch('num', function (value) {
      console.log(value);
    })
    ele.on('blur', function () {
      console.log($scope.num, $scope.min, $scope.max);
    })
  }
  return {
    restrict : 'A',
    scope: {
      num: "=ngModel",
      min: "=?",
      max: "=?"
    },
    link: link
  }
});

output: undefined 5 10

What am I doing wrong?


Solution

  • Instead of using a binding to ngModel, require it and inject it into the link function:

    myApp.directive('myDirective', function () {
      function link($scope, ele, attr, ngModel) { // <--- inject
        $scope.$watch(() => ngModel.$viewValue, (n, o) => {
          // watching `ngModel.$viewValue`
          console.log('WATCH', n, o);
        })
        ele.on('blur', function () {
          // `ngModel.$viewValue` is the current value
          console.log('BLUR', ngModel.$viewValue, $scope.min, $scope.max);
        })
      }
      return {
        require: 'ngModel', // <--- require 
        restrict : 'A',
        scope: {  // <--- remove `ngModel` binding from scope
          min: "=?",
          max: "=?"
        },
        link: link
      }
    });
    

    Here is a demo