2017-02-16 106 views
1

嗨,我有一个按钮,需要根据条件启用或禁用。 需要禁用时,我需要显示一条消息。但是,JavaScript会多次触发,因此多次显示该消息只需显示一次。如何防止Javascript被多次触发

下面是一个调用JavaScript函数的标记: -

<button type="submit" class="btn btn-save nm" ng-click="controller.saveOpportunity()" ng-disabled="!(controller.canDealBeClosedByFeeAllocationStatus() && controller.isEnabled('SaveOpportunity'))"> 
       <svg><use xlink:href="../Content/images/c/svg-defs.svg#circle-check"></use></svg> 
       Save 
      </button> 

下面是JavaScript函数: -

canDealBeClosedByFeeAllocationStatus:()-> 
    if this.isReibDeal() && this.data.OpportunitySalesStageIsClose() == true 
     if this.data.FeeAllocationComplete == false 
     ShowMessage('warning', 'Fee Allocation needs to be complete') 
     return this.data.FeeAllocationComplete 
    else 
     return true 

什么是解决这个问题?

回答

0

使用NG-禁用

<button ng-disabled="IsDisabled" type="submit" class="btn btn-save nm" ng-click="controller.saveOpportunity()" ng-disabled="!(controller.canDealBeClosedByFeeAllocationStatus() && controller.isEnabled('SaveOpportunity'))"> 
       <svg><use xlink:href="../Content/images/c/svg-defs.svg#circle-check"></use></svg> 
       Save 
      </button> 

在控制器

$scope.isDisabled=false; 

在你的JavaScript功能 设置$scope.IsDisabled=true;

当函数执行一次 设置$scope.IsDisabled=true

0

您不应该有这么大的函数检查是否禁用了某些功能,因为ng-disabled可能会多次检查该方法。

NG-禁用,可能被触发,例如,即使你使用的东西无关的NG-禁用方法NG单击see console in this example

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

 
app.controller('MainCtrl', function($scope) { 
 
    $scope.testClick = function(){ 
 
    console.log("click which does not affect disabled flag"); 
 
    }; 
 
$scope.isDisabled=function(){ 
 
    console.log("disabled check function triggered"); 
 
    return true 
 
    
 
}; 
 
});
<!DOCTYPE html> 
 
<html ng-app="plunker"> 
 

 
    <head> 
 
    <meta charset="utf-8" /> 
 
    <title>AngularJS Plunker</title> 
 
    <script>document.write('<base href="' + document.location + '" />');</script> 
 
    <link rel="stylesheet" href="style.css" /> 
 
    <script data-require="[email protected]" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script> 
 
    <script src="app.js"></script> 
 
    </head> 
 

 
    <body ng-controller="MainCtrl"> 
 
    <p>Hello {{name}}!</p> 
 
    <div> 
 
     <button ng-click="testClick()">Test</button> 
 
     <button ng-disabled="isDisabled()">Test</button> 
 
     Test {{message}} 
 
    </div> 
 
    
 
    </body> 
 

 
</html>

所以,更好的方法是有ng-disable监听一个标志变量,如isDealBeClosedByFee,你可以沿着路径或者在控制器初始化时更新它。