0

I have problem and question to my angularJS code. So, I need set new class after click link. My main problem is it, that I have some links in angular and a few in php.

Example;

<li
    <a  href="/somelink>angular link</a>

</li>
  <li
    <a  href="/somelink2>angular link 2</a>

</li>
  <li
    <a  href="/somelink3>angular link 3</a>

</li>

  <li
    <a  href="/somelink 4> Normal link - reload page</a>

</li>  

code which set class on the current link after reload page

  var selector = $('a[href^="' + $(location).attr('href') + '"]');
  selector.addClass('LinkToMenu').parent().addClass('menu-active-border')

I wrote a some jquery code which add class after realod page to current adres, but i have now two problems;

1 If I'm on php page and click angular page, browser realod page and my link gets needed classs - it's ok, but now if I try click other angular page I can't remove this class, how do it ?

2 I wrote some angular code which (example above) add class after click angular link, but it causes problems because if I try move from php page to angular page class is set before reload page yet.

summary;

1 FROM php page -> angular view I need set class after reload page, not immediately after click. 2 change class after click angular link (immediately), remove older and add current class.

1 Answer 1

1

If I understand you correctly, you're asking how to add and remove CSS classes in angularjs. You can use ng-class to add conditional classes.

<a href="/somelink2" ng-class="{'menu-active-border': isLinkActive('/somelink2')}">angular link 2</a>

Where your function isLinkActive would look something like this:

$scope.isLinkActive = function(path) {
  return $location.path() == path;
}

Another option is to create your own directive and manipulate classes there:

<a href="/somelink" highlight-if-active></a>

myApp.directive('highlightIfActive', [function($location){
    return {
        restrict: 'A',
        link: function($scope, $element, $attrs) {
            if ($location.href() == $attrs.href) {
              $element.addClass('menu-active-border');
            } else {
              $element.removeClass('menu-active-border');
            }
        }
    }
}]);
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.