I currently have a user input and an Go tag (code below). I'm trying to validate the user's input on the click of the "Go" button. But the page keep redirecting regardless of validation.
I feel like it'd be best to just use the href
to go the the event/:eventid
route. Is there a way to validate it before the page redirects? Thanks!
view
<div class="small-9 columns">
<input ng-model="vm.eventid" class="event-id" type="text" placeholder="Event ID" maxlength="7">
</div>
<div class="small-3 columns">
<a ng-click="vm.validate()" href="/#/event/{{ vm.eventid }}" class="button postfix event-submit">Go</a>
</div>
<div role="alert" ng-show="vm.formError" class="alert alert-danger">{{ vm.formError }}</div>
controller
(function() {
angular
.module('eventApp')
.controller('homeCtrl', homeCtrl);
homeCtrl.$inject = ['$scope'];
function homeCtrl ($scope) {
var vm = this;
vm.title = "Monitor";
vm.formData = {};
vm.validate = function() {
vm.formError = "";
if (!vm.eventid) {
vm.formError = "Please enter Event ID";
$event.preventDefault();
return false;
} else {
vm.formError = vm.eventid + " entered";
$event.preventDefault();
return false;
}
};
}
})();
答案 0 :(得分:1)
您应该将$event
对象从模板传递到控制器中。使用Angular时,您还应在锚标记中使用ng-href
而不是href
。所以你的代码应该是这样的:
vm.validate = function($event) {
vm.formError = "";
if (!vm.eventid) {
vm.formError = "Please enter Event ID";
$event.preventDefault();
return false;
} else {
vm.formError = vm.eventid + " entered";
$event.preventDefault();
return false;
}
};
你的模板:
<div class="small-3 columns">
<a ng-click="vm.validate($event)" ng-href="/#/event/{{ vm.eventid }}" class="button postfix event-submit">Go</a>
</div>