impregnable fiend impregnable fiend - 1 year ago 51
AngularJS Question

Angular few events on one button

learning Angular, met another issue in my way, hope anyone can help.
I've got one button that must perform two actions: download something and send formdata to the server. So I've wrote this:

<form id='download'>
<label for='name'>Name:</label>
<input type='name' ng-model='nameValue'>
<label for='email'>Email:</label>
<input type='email' id='email' ng-model='emailValue'>

<a ng-click='sendFormDataIfVal()' href="{{filename}}" download="{{filename}}">Download</a>

But the problem and my question is - now downloading and sending occur simultaneously while I wanna download file only if emailValue pass validation and nameValue is not empty. Suppose it's gonna be something like this, but I dunno how to complete function

$scope.sendFormDataIfVal = function() {
$scope.validateEmail() && $scope.sendFormData(); // download & send
if(!$scope.validateEmail()) {
// do not download and do not send

Any advise will be greatly... u know :)

Answer Source

One approach is to disable the link using css. once enabled, both the click event handler and the native download function will work.

toggle the link's 'disabled' css class via a validation function

here is a working example


  <body ng-app="myApp" ng-controller="myController">
        <form id="download">
          <label for="name">Name:</label>
          <input type="name" ng-model="nameValue" />
          <label for="email">Email:</label>
          <input type="email" id="email" ng-model="emailValue" />
        <a ng-class="{'disabled' :  !isFormValid()}"  ng-click="sendFormData()" ng-href="{{fileUrl}}" download="{{fileName}}" >Download</a>


 var myApp = angular.module('myApp',[]);

    myApp.controller('myController', ['$scope', function($scope) {
      $scope.emailValue = '';
      $scope.nameValue = ""; 
    $scope.fileUrl = "";
    $scope.fileName = "funny-cat.jpeg";

      $scope.isEmailValid = function(){
        //replace this simplified dummy code with actual validation
        return $scope.emailValue.indexOf('@') !== -1;


      $scope.isFormValid = function(){

      return   $scope.isEmailValid() &&  $scope.nameValue.length;


      $scope.sendFormData = function(){

        console.log('sent that data');




/*simulate disabled using css, since this property is nto supported on anchor element*/