0

I used to have controller in whole <body ng-controller="MainCtrl">, where I had some basic functions like this one:

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

Used here:

 ng-class="{active:isActive('{{ $link['url'] }}')}"

What's best way how to handle that? It's used in many times on different lists. Should I make a directive?

2
  • you can use ui-sref-active.. Commented Jul 9, 2015 at 13:15
  • Why you confusing this much??? Commented Jul 9, 2015 at 13:19

2 Answers 2

1

In general, you handle re-occurring functions with services (tutorial), like this:

angular.module('yourAppName').service('yourServiceName', function(){
        return {
            isActive: function (route){
                return route === $location.path();
            },
});

Then, in your controller, add a dependency on 'yourServiceName' and call yourServiceName.isActive(route) anytime you want to use it.

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

7 Comments

Aside from the general point you make in your answer, I think this is exactly what he means. If I understand correctly, he asks how to handle reoccuring functions and you answered that. JqueryKing's answer is about changing syntax, but I don't think the syntax was a problem in his case.
JqueryKing's answer is useless for me because my syntax also works. I was asking how to handle that situation without needing some controller work. Generally how to add class to a link in active route
Do you have the solution you need or is there something I can clarify for you? Let me know if you need more tutorial links/clarification. I edited to remove the "other answers" part.
Service is probably not that what I need for this. I have plenty of links <a href="/#/something">something</a> and I wanna add there active class if current url is something
scotch.io/tutorials/the-many-ways-to-use-ngclass I am pretty sure ng-class is the second part of what you need (for assigning classes based on conditions). Let me think about this for a second and then I will update the answer.
|
0

change

ng-class="{active:isActive('{{ $link['url'] }}')}"

to

ng-class="{'active': isActive($link['url'])}"

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.