我的指示如下:
directive('checkKey', function() {
return {
restrict: 'A',
scope: {
min: '='
},
link: function(scope, elem, attrs) {
elem.bind('keypress', function(event) {
if (event.keyCode === 46 || event.keyCode === 45) {
event.preventDefault();
return false;
} else if (event.key < scope.min) {
event.preventDefault();
return false;
}
});
}
}
})
但我无法访问输入模型值...
答案 0 :(得分:1)
您需要要求ngModel,然后将ngModelCtrl注入您的链接。该值将在ngModelCtrl中。
directive('checkKey', function() {
return {
restrict: 'A',
require: 'ngModel',
scope: {
min: '='
},
link: function(scope, elem, attrs, ngModelCtrl) {
// this would give you the ngModel value also.
var ngModelVal = $parse(attrs.ngModel);
elem.bind('keypress', function(event) {
if (event.keyCode === 46 || event.keyCode === 45) {
event.preventDefault();
return false;
} else if (event.key < scope.min) {
event.preventDefault();
return false;
}
});
}
}
})
答案 1 :(得分:0)
您可以require
指令中的ngModel
控制器。您可以通过$setViewValue
设置ngModel值,并通过$modelValue
var myApp = angular.module('myApp',[]);
myApp.directive('myDirective', function($timeout) {
return {
restrict: 'EA',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
console.log("$modelValue", ngModel);
ngModel.$render = function() {
$timeout(function() {
ngModel.$setViewValue('I am updated');
}, 5000);
};
}
};
});
function MyCtrl($scope) {
$scope.name = 'Vinoth';
}