1

I have a controller like this which is attached to body of html.

angular.module("app", [])

.controller("MyCtrl", function($scope) {

   // Here I perform some jquery code listening for click event

   $("a").click(function() {
      $(this).toggleClass("active");
   });

});

Now, I want to know why this doesn't work inside controller. I know, if I put it into directive then it does work.

Ashish Rawat
  • 3,363
  • 5
  • 29
  • 35

1 Answers1

1

Don't mix up JQuery with AngularJS, Since its not a Good Practice,

If you want some toggle feature use in-built ngClick directive feature provided by AngularJs instead of using JQuery $("a").click

Sample Demo 1

Sample Demo 2

Sample Demo 3

Sample Demo 4

function MainController($scope) {
  $scope.toggle = true;
}
.box {
  color: white;
  text-align: center;
  height: 100px;
  font-size: 86px;
}
.on {
  background-color: green;
}
.off {
  background-color: red;
}
.box-show-setup,
.box-hide-setup {
  -webkit-transition: all linear 0.3s;
  -moz-transition: all linear 0.3s;
  -ms-transition: all linear 0.3s;
  -o-transition: all linear 0.3s;
  transition: all linear 0.3s;
}
.box-show-setup {
  opacity: 0;
  height: 0;
}
.box-show-setup.box-show-start {
  opacity: 1;
  height: 100px;
}
.box-hide-setup {
  opacity: 1;
  height: 0;
}
.box-hide-setup.box-hide-start {
  opacity: 0;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="MainController">
  <button ng-click="toggle = !toggle">Toggle!</button>

  <div class="box on" ng-show="toggle" ng-animate="'box'">On</div>
  <div class="box off" ng-hide="toggle" ng-animate="'box'">Off</div>
</div>

Also read this beautiful stuff

Using AngularJS? Stop using jQuery as a crutch.

Community
  • 1
  • 1
Nidhish Krishnan
  • 20,593
  • 6
  • 63
  • 76