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.

9
  • 2
    What do you mean, it doesn't work? Be a bit more specific. Commented Nov 17, 2014 at 9:30
  • Not a direct answer, but in my opinion, DOM operations should never be inside controller. Is there some specific purpose for this approach? Like you said, it works in directive. Commented Nov 17, 2014 at 9:31
  • I think you should read again what an AngularJs controller is. That function you defined is used as a constructor Commented Nov 17, 2014 at 9:32
  • Please place whole code here..how are you trying to access this controller. If possible also make a plunker of it. Commented Nov 17, 2014 at 9:32
  • In that code do an alert($("a").length) Commented Nov 17, 2014 at 9:32

1 Answer 1

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.

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

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.