我正在尝试创建一个执行以下操作的指令:
以下是使用链接功能的代码:
app.directive('rangedInput', function ($parse) {
return {
scope: {
lower: "@",
upper: "@",
},
require: 'ngModel',
link:
function ($scope, element, attrs, ngModelCtrl) {
if (!ngModelCtrl) {
return;
}
element.bind('blur', function (event) {
event.preventDefault();
var value = parseInt(element.val());
var upper = parseInt($scope.upper);
var lower = parseInt($scope.lower);
if (value > upper) {
value = upper;
} else if (value < lower) {
value = lower;
}
$scope.$apply(function () {
ngModelCtrl.$setViewValue(value);
ngModelCtrl.$render();
});
});
}
};
});
用法:
<label>{{model.Amount}}</label>
<input type="text" upper="1500000" lower="50000" ranged-input ng-model="model.Amount" />
我也尝试过使用编译功能:
app.directive('rangedInput', function ($parse) {
return {
scope: {
lower: "@",
upper: "@",
},
require: 'ngModel',
compile: function () {
var getter, setter;
return function ($scope, element, attrs, ngModelCtrl) {
getter = $parse(attrs.ngModel);
setter = getter.assign;
if (!ngModelCtrl) {
return;
}
element.bind('blur', function (event) {
event.preventDefault();
var value = parseInt(element.val());
var upper = parseInt($scope.upper);
var lower = parseInt($scope.lower);
if (value > upper) {
value = upper;
}
else
if (value < lower) {
value = lower;
}
element[0].value = value;
$scope.$apply(function () {
setter($scope, value);
});
});
};
}
};
});
两者都没有按预期工作,我发现的问题是ng-model="model.Amount"
的值似乎无法正确更新?
答案 0 :(得分:0)
这是固定代码。看一下这个。
app.directive('rangedInput', function ($parse) {
return {
scope: {
lower: "@",
upper: "@",
},
require: 'ngModel',
link:
function ($scope, element, attrs, ngModel) {
if (!ngModel) {
return;
}
element.bind('blur', function (event) {
event.preventDefault();
var value = parseInt(element.val());
var upper = parseInt($scope.upper);
var lower = parseInt($scope.lower);
if (value > upper) {
value = upper;
} else if (value < lower) {
value = lower;
}
$scope.$apply(function () {
ngModel.$setViewValue(value);
ngModel.$render();
});
});
}
};
});