Salman
Salman

Reputation: 1286

unbind ng-click dynamically from element : angularjs

i have an element which have ng-click event and on clicking it adds a div that works fine. what i want is to remove ng-click after adding the div .

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 div for single element that works on and off. is there any way to unbind click event like we do in jquery dynamically?

any help will be appreciated

Upvotes: 4

Views: 6275

Answers (3)

LionC
LionC

Reputation: 3106

Put that logic into the controller, not into the view

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>

Upvotes: 2

Joao Leal
Joao Leal

Reputation: 5542

You can also do this:

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

This will prevent ng-click from calling addDiv() if divAdded is true

Upvotes: 2

DonJuwe
DonJuwe

Reputation: 4563

You can do it in a more easy way like this:

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>

Upvotes: 0

Related Questions