impregnable fiend impregnable fiend - 5 months ago 12
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'>
</form>

<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

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

HTML

  <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" />
        </form>
        <a ng-class="{'disabled' :  !isFormValid()}"  ng-click="sendFormData()" ng-href="{{fileUrl}}" download="{{fileName}}" >Download</a>
      </body>

JS

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

    myApp.controller('myController', ['$scope', function($scope) {
      $scope.emailValue = 'sample@email.com';
      $scope.nameValue = ""; 
    $scope.fileUrl = "http://thatfunnyblog.com/wp-content/uploads/2014/03/funny-videos-funny-cats-funny-ca.jpg";
    $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');

      }

    }]);

CSS

a.disabled{ 
/*simulate disabled using css, since this property is nto supported on anchor element*/
color:gray;
pointer-events:none;

}