如何在指令中获取 ng-model 值

how to get ng-model value in directive

我在AngularJS中写了一个指令,并使用了具有min-max和ng-model属性的输入类型编号。我使用了隔离范围。在指令中,我写了一个模糊事件。我得到最小值-最大值但没有得到 ng-model 值:

<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

我做错了什么?

而不是使用绑定到 ngModelrequire 它并将其注入 link 函数:

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
  }
});

这是一个demo