Cập nhật:
Phiên bản cải tiến và đơn giản hóa của chỉ thị trước đó (một thay vì hai) với cùng chức năng:
.directive('myTestExpression', ['$parse', function ($parse) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
var expr = attrs.myTestExpression;
var watches = attrs.myTestExpressionWatch;
ctrl.$validators.mytestexpression = function (modelValue, viewValue) {
return expr == undefined || (angular.isString(expr) && expr.length < 1) || $parse(expr)(scope, { $model: modelValue, $view: viewValue }) === true;
};
if (angular.isString(watches)) {
angular.forEach(watches.split(",").filter(function (n) { return !!n; }), function (n) {
scope.$watch(n, function () {
ctrl.$validate();
});
});
}
}
};
}])
Ví dụ sử dụng:
<input ng-model="price1"
my-test-expression="$model > 0"
my-test-expression-watch="price2,someOtherWatchedPrice" />
<input ng-model="price2"
my-test-expression="$model > 10"
my-test-expression-watch="price1"
required />
Kết quả: Các biểu thức kiểm tra phụ thuộc lẫn nhau trong đó các trình xác nhận được thực thi khi thay đổi mô hình chỉ thị và mô hình hiện tại khác.
Biểu thức kiểm tra có $model
biến cục bộ mà bạn nên sử dụng để so sánh nó với các biến khác.
Trước đây:
Tôi đã cố gắng cải thiện mã @Plantface bằng cách thêm chỉ thị bổ sung. Lệnh bổ sung này rất hữu ích nếu biểu thức của chúng ta cần được thực thi khi các thay đổi được thực hiện trong nhiều hơn một biến ngModel.
.directive('ensureExpression', ['$parse', function($parse) {
return {
restrict: 'A',
require: 'ngModel',
controller: function () { },
scope: true,
link: function (scope, element, attrs, ngModelCtrl) {
scope.validate = function () {
var booleanResult = $parse(attrs.ensureExpression)(scope);
ngModelCtrl.$setValidity('expression', booleanResult);
};
scope.$watch(attrs.ngModel, function(value) {
scope.validate();
});
}
};
}])
.directive('ensureWatch', ['$parse', function ($parse) {
return {
restrict: 'A',
require: 'ensureExpression',
link: function (scope, element, attrs, ctrl) {
angular.forEach(attrs.ensureWatch.split(",").filter(function (n) { return !!n; }), function (n) {
scope.$watch(n, function () {
scope.validate();
});
});
}
};
}])
Ví dụ về cách sử dụng nó để tạo các trường được xác thực chéo:
<input name="price1"
ng-model="price1"
ensure-expression="price1 > price2"
ensure-watch="price2" />
<input name="price2"
ng-model="price2"
ensure-expression="price2 > price3"
ensure-watch="price3" />
<input name="price3"
ng-model="price3"
ensure-expression="price3 > price1 && price3 > price2"
ensure-watch="price1,price2" />
ensure-expression
được thực thi để xác nhận mô hình khi ng-model
hoặc bất kỳ ensure-watch
biến nào được thay đổi.