2017-03-20 38 views
1

如何在使用特定計數動態創建元素後禁用按鈕。我的意思是說,我想點擊一個按鈕創建5 div的動態後禁用按鈕....這是可能的角JS動態創建元素後禁用按鈕

我給小提琴enter code here HTML的URL

<div ng-app="myApp" ng-controller="customersCtrl"> 
<button ng-click="createElement()" id="btnCreateElement"ng-disabled="isDisabled">ClickToAdd</button> 

<div id="target"> 

</div> 
<button ng-click="toogleElement()">ClickToAdd</button> 
<div class="tryIt" ng-if="showDiv"></div> 
<div class="tryIt" id="redDiv" ng-if="!showDiv"></div> 

JS

var app = angular.module('myApp', []); 
app.controller('customersCtrl', function($scope) { 
$scope.showDiv=true; 
$scope.isDisabled =false; 

$scope.createElement =function(){ 
    var newDiv = angular.element('<div class="test"></div>'); 
    var newDivContainer = document.getElementById("target"); 
    angular.element(newDivContainer).append(newDiv); 
    $scope.isDisabled =true; 

} 
$scope.toogleElement=function(){ 
    $scope.showDiv =!$scope.showDiv; 
} 


}); 

CSS

.test{width:400px;height:30px;background:green;margin:10px 0;} 
    .tryIt{width:200px;height:200px;background:#00B3E3;margin-left:50%; position:relative;} 
    #target>div:nth-child(5){background:blue;} 
    #redDiv{background:red;} 
    #btnCreateElement{cursor:pointer;} 
    #btnCreateElement:disabled{cursor:no-drop;} 

https://jsfiddle.net/e61rdhtb/1/

+0

嘗試添加計數器對創建的div –

+0

,你可以請更新FIDDLE @賈揚特·PATIL –

回答

1

你應該用一個計數器變量來跟蹤點擊請求的數量和禁用連續動作

示例代碼

$scope.createElement = function() { 
    if (clicks == 5) { 
     $scope.isDisabled = true; 
    } else { 
     var newDiv = angular.element('<div class="test"></div>'); 
     var newDivContainer = document.getElementById("target"); 
     angular.element(newDivContainer).append(newDiv); 
     clicks += 1; 
     if (clicks == 5) { 
      $scope.isDisabled = true; 
     } 
    } 
} 

Fiddle

+0

感謝洙多 –

+0

我很高興幫助 –

+0

,但有問題,它禁用按鈕在第6點擊 –

1

可以保持在控制器的一個計數變量。

$scope.count=0; 
$scope.createElement =function(){ 
// your code 
$scope.count++; 
} 

而且在UI添加條件,使按鈕後點擊5次

被禁用
<button ng-click="createElement()" id="btnCreateElement" ng-disabled="count==5">ClickToAdd</button> 
+0

謝謝sooo多Dude ...它的作品 –