Kenny
Kenny

Reputation: 2144

Angular <a> ng-click function validate before redirect

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;
            }
        };
    }

})();

Upvotes: 0

Views: 1041

Answers (1)

arjabbar
arjabbar

Reputation: 6404

You should be passing in the $event object from your template into the controller. You should also use ng-href instead of href in anchor tags when using Angular. So your code should look like this:

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;
            }
        };

And your template:

<div class="small-3 columns">
    <a ng-click="vm.validate($event)" ng-href="/#/event/{{ vm.eventid }}" class="button postfix event-submit">Go</a>
</div>

Upvotes: 1

Related Questions