[英]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.