[英]how to get ng-model value in directive
我在 AngularJS 中编写了一个指令,并使用了具有 min-max 和 ng-model 属性的输入类型编号。 我使用了隔离的 scope。 在指令中,我写了一个模糊事件。 我得到 min-max 值但没有得到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:未定义 5 10
我究竟做错了什么?
不要使用绑定到ngModel
,而是require
它并将其注入到链接 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
}
});
这是一个演示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.