0

On page load the console log prints but the toggleClass/click won't work I even use angular.element but it has the same result.I need to change state in order for the toggleClass to work.I dunno what's wrong in my code.

    .run(['$rootScope', function ($rootScope) {
        console.log('test');//this prints test and it's ok       

	//this part won't load at the first loading of page.
                $('.toggle-mobile').click(function(){
                    $('.menu-mobile').toggle();
                    $(this).toggleClass('toggle-click');
                });
    //....
   }])

even doing it this way doesn't work.

            $rootScope.$on('$viewContentLoaded', function () {

                angular.element('.toggle-mobile').on('click', function (event) {
                    angular.element(this).toggleClass('toggle-click');
                    angular.element('.menu-mobile').toggle();
                    event.preventDefault();
                });

            });

1
  • Turning it into a directive works. Commented Sep 17, 2014 at 17:24

1 Answer 1

1

The Angular way to render items is different from "On DOM Ready" that is why we need to treat these as 2 separate things.

Angular could render items later on even after DOM is ready, this could happen for example if there is an AJAX call($http.get) and that is why a directive may be the recommended approach.

Try something like this:

<body ng-controller="MainCtrl">
  <div toggle-Me="" class="toggle-mobile"> Sample <div class="menu-mobile">Sample 2</div>
  </div>

<script>

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

myApp.controller('MainCtrl', ['$scope', function ($scope) {}]);

myApp.directive("toggleMe", function() {
    return {
            restrict: "A", //A - means attribute
            link: function(scope, element, attrs, ngModelCtrl) {
              $(element).click(function(){
                $('.menu-mobile').toggle();
                $(this).toggleClass('toggle-click');
             });
            }
        };
});

...

By declaring the directive myApp.directive("toggleMe",... as an attribute toggle-Me="" every time angular generates the input element it will execute the link function in the directive.

Disclaimer: Since the post lacks from a sample html I made up something to give an idea how to implement the solution but of course the suggested html is not part of the solution.

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

3 Comments

@gabmon I added more details to explain, hope it helps
Directives work to this thanks.I already turn it into directive a minute before this answer came.
You can just use the class as it is. plnkr.co/edit/dCRJ0aMYBcnpFeiCotas?p=preview

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.