<ng-form name="myForm">
<div ng-show="myForm.text{{$index}}.$error.printValidator">
you cannot print {{data}} !!
</div>
<div>
<textarea name="text{{$index}}" placeholder="{{textSection.text}}" ng-model="getUserTextSction(textSection.textStyleID, area.userPageText).text" print-validator ng-model-options="{updateOn: 'blur'}"> </textarea>
</div>
</ng-form>
<a ng-disabled="myForm.$invalid" ng-click='completeEditPage("/article/")'>
上面是我的html代码,下面是javascript代码
angular.module('editorApp')
.directive('printValidator', function ($http, $q,baseService) {
return {
restrict: "A",
require: "ngModel",
link: function (scope, element, attrs, ngModel) {
var checkPrintable = function (modelValue, viewValue) {
var deferred = $q.defer();
var value = modelValue || viewValue;
var param = {};
param.text = value;
return $http.post(
'/api/edittexts/CheckPrintable/',
param, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
})
.then(function (response) {
if (response.data.ngChar) {
ngModel.$setValidity('printValidator', false);
alert("you cannot print:"+response.data.ngChar);
deferred.reject(response.data);
}
else
{
ngModel.$setValidity('printValidator', true);
deferred.resolve;
}
return deferred.promise;
});
}
ngModel.$asyncValidators.text = checkPrintable;
}
}
})
上面的代码工作得很好。当用户键入不可打印的字符时,它会显示错误消息...
现在我有两个问题: 第一个是如何在“{{data}}”的标签中显示从服务器端传递的不可打印的字符(实际上是“response.data.ngChar”)? (这意味着,如何在html中获取deferred.reject的参数)
第二个是当有不可打印的字符错误时如何禁用提交按钮? 我使用“ng-disabled =”myForm。$ invalid“”但它不起作用。
谢谢。答案 0 :(得分:0)
I see you are doing some very complicated stuff for a very easy job.
How i would set this up is something as the following:
<div ng-if="!data">Fetching data...</div>
<div ng-if="data && data.length > 0">Unprintable characters: {{data}}</div>
<a ng-disabled="data && data.length < 1" ng-click="completeEditPage("/article/")">
Your variable 'data' will be set when the data is retrieved asynchronously. When data is being retrieved, $scope.data will be undefined making your div 'fetching data...' visible
When your variable 'data' gets set by the asynchronous function. the fetching data... div will disappear and you can view another div based on the 'data' not being undefined.
Now the only thing you need to do is set $scope.data when your function finishes.
so... $scope.data = response.data;
(Hoping that your response.data is an array)