4

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

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

That answer doesn't explain why, and nor does your comment. Can you elaborate?
Sure. HTML is a markup language which should describe a layout and (ideally) no behaviour at all. ng-click exists to connect an input to a controller, who has the responsibility to decide what to do with that button click. It is not the decision of the button(the view) to decide what to do with that click - that is exactly what controllers exist for and thus controllers are also the place people will look for code like that. I am pretty sure that that is also the reason why angular expressions do not support an expressive if-construct to this day - because it should not be used.
2

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>

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.