如果验证失败,请尝试将特定类添加到输入。下面是一个简单的测试代码。
控制器:
vm.emsg = '';
if ((parseFloat(vm.sum1) + parseFloat(vm.sum2)) < 100) {
vm.emsg = 'Hey, sum should be 100.';
/*something to add class to input*/
return false;
}
模板:
<form method="POST" enctype="multipart/form-data" ng-submit="vm.save($event)">
<input type="text" ng-model="vm.sum1">
<input type="text" ng-model="vm.sum2">
<div class="error-message" ng-if="vm.emsg">
{[vm.emsg]}
</div>
</form>
答案 0 :(得分:1)
一个选项是使用ngClass
指令评估你的表达式,你也可以评估你的表达式来显示一个合适的消息,如下所示:
// app.js
(function() {
'use strict';
angular.module('app', []);
})();
// main.controller.js
(function() {
'use strict';
angular.module('app').controller('MainController', MainController);
MainController.$inject = [];
function MainController() {
var vm = this;
}
})();
&#13;
.error-message {
color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<div ng-app="app" ng-controller="MainController as vm">
<input type="number" ng-model="vm.sum1">
<input type="number" ng-model="vm.sum2">
<div ng-class="{'error-message': vm.sum1 + vm.sum2 !== 100}">
{{vm.sum1 + vm.sum2 !== 100 ? 'Hey, sum should be 100.' : ''}}
</div>
{{vm.sum1 + vm.sum2}}
</div>
&#13;
或者您可以使用ngIf
指令来显示您的消息:
// app.js
(function() {
'use strict';
angular.module('app', []);
})();
// main.controller.js
(function() {
'use strict';
angular.module('app').controller('MainController', MainController);
MainController.$inject = [];
function MainController() {
var vm = this;
vm.sumsInvalid = sumsInvalid;
function sumsInvalid() {
// simply return true to display the error message via the ngIf directive
return parseFloat(vm.sum1) + parseFloat(vm.sum2) !== 100;
}
}
})();
&#13;
.error-message {
color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<div ng-app="app" ng-controller="MainController as vm">
<input type="number" ng-model="vm.sum1">
<input type="number" ng-model="vm.sum2">
<div class="error-message" ng-if="vm.sumsInvalid()">
Hey, sum should be 100.
</div>
<p>{{vm.sum1 + vm.sum2}}</p>
</div>
&#13;