Unbind ng-click dynamically from element: angularjs

I have an element that has an ng-click event and when clicked it adds a div which works great. i want to remove ng-click after div is added.

one way is to use ng-if

  <div ng-click="addDiv()" ng-if="!divAdded" >                   
                        <span>i add a div</span> 
               </div>

 <div class="disabled" ng-if="divAdded" >                   
                        <span>i add a div</span> 
               </div>

      

for this i have to add multiple divs for one element that works on and off. is there a way to disable the click event like we do in jquery dynamically?

any help would be appreciated

+3


source to share


3 answers


You can also do this:

<div ng-click="divAdded || addDiv()" >                   
    <span>i add a div</span> 
</div>

      



This will prevent ng-click from being called from addDiv()

if divAdded

true

+2


source


Put this logic in controller

, not inview

Controller:

(function(){

function divAddController() {
    var self = this;

    self.divAdded = false;

    self.addDiv = function() {
        if(!divAdded) { 
            //Add div here
            self.divAdded = true;
        }
    }
}

angular.module("example")
.controller("divAddController", divAddController);

})();

      



View:

<div ng-controller="divAddController as divAdder">
    <div ng-click="divAdder.addDiv()" ng-class="{disabled: divAdder.divAdded}">
        <span>i add a div</span>
    </div>
</div>

      

+2


source


You can do it in an easier way:

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

myApp.controller('MyCtrl', function($scope) {
  $scope.showDiv = false;
});
      

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="MyCtrl">
  <button ng-click="showDiv = true;">I show the div</button>
  <div ng-if="showDiv">I am visible!</div>
</div>
      

Run codeHide result


0


source







All Articles