我正在尝试弄清楚是否可以验证数据客户端以确保没有重复项被发送到数据库。我有一个 Angular 应用程序,它从 api 调用中获取数据。这是我当前用于添加新主题的 Controller (功能完美,但没有数据验证):
angular.module('myApp.controllers')
.controller('SubjectNewCtrl', ['$scope', 'SubjectsFactory', '$location', '$route',
function ($scope, SubjectsFactory, $location, $route) {
// callback for ng-click 'createNewSubject':
$scope.createNewSubject = function () {
SubjectsFactory.create($scope.subjects);
$location.path('/subjects');
}
}]);
这是我一直在尝试的数据验证:
angular.module('myApp.controllers')
.controller('SubjectNewCtrl', ['$scope', 'SubjectsFactory', '$location', '$route',
function ($scope, SubjectsFactory, $location, $route) {
// callback for ng-click 'createNewUser':
$scope.createNewSubject = function () {
var newSubject = $scope.subject.name;
var someSubject = $scope.subjects;
var oldSubject;
if(newSubject){
angular.forEach($scope.subjects, function(allSubjects){
if(newSubject.toLowerCase() == allSubjects.name.toLowerCase()){
oldSubject = true;
}
});
if (!oldSubject){
SubjectsFactory.create($scope.subjects);
}
}
}
}]);
这给了我一个控制台错误 - TypeError: Cannot read property 'name' of undefined
。如何从 html 访问我的新主题的“名称”属性?谁能告诉我我正在尝试做的事情是否可行/有意义吗?
最佳答案
如果我正确理解您的问题,您应该针对您要验证的特定字段使用指令。一个独特的电子邮件指令是一个常见的例子。这是我过去用过的一个。没什么特别的。
MyApp.directive('uniqueEmail', ['$http', function($http) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
//set the initial value as soon as the input comes into focus
element.on('focus', function() {
if (!scope.initialValue) {
scope.initialValue = ctrl.$viewValue;
}
});
element.on('blur', function() {
if (ctrl.$viewValue != scope.initialValue) {
var dataUrl = attrs.url + "?email=" + ctrl.$viewValue;
//you could also inject and use your 'Factory' to make call
$http.get(dataUrl).success(function(data) {
ctrl.$setValidity('isunique', data.result);
}).error(function(data, status) {
//handle server error
});
}
});
}
};
}]);
然后在您的标记中,您可以像这样使用它。
<input type="text" name="email" ng-model="item.email" data-unique-email="" data-url="/api/check-unique-email" />
<span class="validation-error" ng-show="form.email.$error.isunique && form.email.$dirty">Duplicate Email</span>
希望这就是您要找的。p>
关于javascript - angularJS 中的客户端重复数据验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22203677/