2016-06-21 49 views
0

学习Angular,在我的路上遇到了另一个问题,希望任何人都可以提供帮助。 我有一个按钮,必须执行两个操作:下载一些东西并将formdata发送到服务器。所以我写了这个:在一个按钮上的角度几个事件

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

但问题和我的问题是 - 现在下载和发送,同时我想下载文件只有emailValue通过验证和nameValue不是空的同时发生。假设它会是这样的,但我不知道如何完成的功能

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

任何建议将大大...你知道:)

回答

1

一种方法是禁用使用CSS的链接。 一旦启用,click事件处理程序和本机下载功能都将起作用。

拨动通过验证函数

这里链接的 '禁用' CSS类是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 = '[email protected]'; 
     $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; 

} 
+0

哇,太好了!谢谢10亿次,男子 –

+0

很高兴帮助:)快乐编码 – CodeToad

+0

我可以问你多一个问题吗?) –

0

试试这个:

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