我是angularjs的新手,目前我有一个电子邮件输入表单。
<div ng-app="emailApp" ng-controller="emailController">
<form name="emailSubmitForm">
<div>
<input name="emailInput" type="email" ng-model="email" ng-watchchange="checkduplicate(email)" ng-pattern="emailFormat" required />
</div>
<div ng-show="isRepeated">Repeated</div>
<div ng-show="!isRepeated">Not Repeated</div>
<button ng-disabled="emailSubmitForm.$invalid" ng-click="createRecord()" >Submit</button>
</form>
</div>
最初我使用ng-change但是如果它无效则不会触发,因此我想将ng-change函数更改为指令,但我不知道如何去做。
我想更改下面的功能
$scope.checkduplicate = function (email) {
var model= {
email: email
};
$http({
method: 'POST',
url: '/Controller/IsEmailDuplicated',
data: model
}).success(function (data, status, headers, config) {
$scope.isRepeated = !data;
});
};
类似
app.directive('ngWatchchange',function(email){
// $http.post request
});
有人能给我一些建议吗?非常感谢!
答案 0 :(得分:1)
如果你不能使用ng-change,我会使用$ watch(在你的控制器或单独的指令中,但我不会这样做)。 在您的控制器中有这样的东西:
$scope.$watch(function () { return $scope.email },
function (changedEmail) {
var model= {
email: email
};
$http({
method: 'POST',
url: '/Controller/IsEmailDuplicated',
data: model
}).success(function (data, status, headers, config) {
$scope.isRepeated = !data;
});
});
这样,您可以在每次更改电子邮件时发送$ http(但您可以根据需要对其进行个性化设置)。
如果仍然继续使用指令,您可以尝试:
app.directive('ngWatchchange', function() {
return {
restrict: 'A',
scope: {
ngWatchchange: '='
},
link: function(scope, element, attr) {
$scope.$watch(function () { return scope.ngWatchchange },
function (changedEmail) {
var model= {
email: email
};
$http({
method: 'POST',
url: '/Controller/IsEmailDuplicated',
data: model
}).success(function (data, status, headers, config) {
$scope.isRepeated = !data;
});
});
}
};
});
答案 1 :(得分:1)
我假设您要创建验证指令,以检查电子邮件是否可用,所以:
<input name="emailInput" type="email" ng-model="email" email-available ng-pattern="emailFormat" required />
<div ng-show="form.emailInput.$error.emailAvailable">Repeated</div>
<div ng-show="!form.emailInput.$error.emailAvailable">Not Repeated</div>
指令:
app.directive('emailAvailable', function ($q, Api) {
return {
require: 'ngModel',
restrict: 'A',
link: function (scope, element, attrs, ctrl) {
ctrl.$asyncValidators.emailAvailable = function(modelValue, viewValue) {
// if value is empty we leave it to 'required' validator
if (ctrl.$isEmpty(modelValue)) {
return $q.when();
}
return $q(function (resolve, reject) { //we need to return promise
$http({
method: 'POST',
url: '/Controller/IsEmailDuplicated',
data: modelValue
}).success(function (data, status, headers, config) {
if (data) {
reject(); // e-mail is duplicate so we reject from promise
} else {
resolve(); // e-mail is not duplicate so we set it as ok
}
});
});
};
}
};
我是从记忆中写的,所以可能会有一些错误,但这个想法应该没问题。