[英]angular directive is not working
我有一個文本框和一條指令來限制在屏幕上顯示負值,並且ng-model應該包含該負值。
在下面的指令,我總是得到""
作為inputValue的價值,如何獲得的inputValue將在NG-模型值
app.directive('numberOnly', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
if (inputValue == undefined) return '';
var transformedInput = inputValue.replace(/[^0-9]/g, '');
if (transformedInput != inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
您的代碼運行良好:
<div ng-app="myModule">
<div ng-controller="myController">
<input type="text" number-only ng-model="model"/>
</div>
</div>
var module = angular.module("myModule", []);
module.controller('myController', ['$scope', function($scope) {
$scope.model = '01234';
}]);
module.directive('numberOnly', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function(inputValue) {
// Value prints here
console.log(inputValue);
if (inputValue == undefined) return '';
var transformedInput = inputValue.replace(/[^0-9]/g, '');
if (transformedInput != inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.