我已经为textarea Html标记编写了一个指令,以便向API提交描述。我提交数据后,我需要不设置此标记。我使用$scope.$setPristine()
然后使用$scope.apply()
,但这不起作用!我也尝试了ngModelCtrl.$setUntouched()
并得到了相同的结果。
指令标签如下:
<div class="col-sm-12">
<dp-text-area
dp-tabindex="11"
label="Description"
placeholder="Description"
ng-model="vm.cityModel.description">
</dp-text-area>
</div>
这是指令JavaScript代码:
function dpTextArea($timeout) {
return {
restrict: 'E',
require: "ngModel",
scope: {
label: '@',
placeholder: '@',
externalNgModel: '=ngModel',
editDisabled: '@',
ngRequired: '=',
dpTabindex: '='
},
link(scope, elm, attr, ngModelCtrl) {
scope.safeApply = function (fn) {
var phase = this.$root.$$phase;
if (phase == '$apply' || phase == '$digest') {
if (fn && (typeof(fn) === 'function')) {
fn();
}
} else {
this.$apply(fn);
}};
scope.$watch(() => {
return scope.editDisabled;
}, (n, o) => {
// if (n == o)return;
if (scope.editDisabled === 'false') {
scope.editDisabled = false;
}
});
scope.isTextareaTouched = false;
scope.isTextareaInvalid = false;
if (scope.ngRequired)
scope.isTextareaInvalid = true;
scope.blurFunc = () => {
scope.isTextareaTouched = true;
};
//#region watch $error
scope.$watch(
function () {
let rtn = JSON.stringify(ngModelCtrl.$error);
return rtn;
},
function (n, o) {
if (n == o) return;
if (Object.keys(ngModelCtrl.$error).length == 0) {
scope.isTextareaInvalid = false;
} else {
scope.isTextareaInvalid = true;
}
});
//#endregion
},
template: require('./dpTextArea.directive.html')
}}
export default angular.module('directives.dpTextArea', [])
.directive('dpTextArea', dpTextArea)
.name;
这是指令的模板:
<div class="form-group" ng-class="{'has-error':isTextareaInvalid && isTextareaTouched}">
<label class="control-label">
{{label || 'description'}}
<sup class="text-danger" ng-show="ngRequired">*</sup>
</label>
<textarea rows="3" type="text"
tabindex="{{dpTabindex}}"
class="form-control"
ng-class="{'edit-disabled':editDisabled}"
ng-disabled="editDisabled"
placeholder="{{placeholder || 'description'}}"
ng-model="externalNgModel"
ng-required="ngRequired"
ng-blur="blurFunc()"
></textarea>
<small class="help-block" ng-show="isTextareaInvalid && isTextareaTouched">this field is requred.</small>
我感谢任何帮助。