Reputation: 712
So I have a navigation list element and I want AngularJS to store which tab is active, then add the 'active' class to that tab any time a reroute happens. I am trying to simply print the active tab's name to the log currently. I haven't linked a function in the 'link' option of a directive before, so my syntax may be wrong.
My navigation directive:
navigation.$inject = ['$modal', 'localStorageService', '$log']
function navigation ($modal, localStorageService, $log) {
var vm = this;
return {
restrict: 'EA',
templateUrl: '/common/directives/navigation/navigation.template.html',
link : function ($scope, $log, localStorageService) {
$scope.setActive = function (tab) {
$scope.active = tab;
$log.debug($scope.active);
}
}
};
}
My HTML (one of my 'pagination' navigation elements):
<li><a href="/#/cw" ng-click="$scope.setActive('cw')">Connect Wise</a></li>
At this point I'm just trying to access whats in link, and print the variable passed into my directive's 'link' function to the console in the browser.
This seems like it should be very easy but I can't figure it out for the life of me.
EDIT: I should add, my current approach is based on this: How to define a function inside Angular-js Directive
Upvotes: 0
Views: 295
Reputation: 8463
IMHO this approach is not particularly true to common AngularJS convention. Using a directive for your navigational needs is probably an over-kill.
Generally speaking the community has embraced Angular UI-Router as a solution for your navigation woes.
If you use ui-router you can add a function to the Navigation controller's scope that checks the $state service for the current state/route to see if the route you''re looking for is currently active.
Even if you are not using ui-router, my advice would be to have a service that tells your application what is your current route and use something like
<a ng-click="goToState('home')" ng-class="{active: isStateActive('home')}">Home</a>
Where $scope.isStateActive(stateName)
is the function on your navigation controller's scope that determines(whether by using ui-router's $state service or your homegrown service if we are currently in the 'home' state and $scope.goToState(stateName)
is a function that initiates the state transition
Upvotes: 1
Reputation: 136154
You messing with HTML as well as directive
HTML
<li><a href="/#/cw" ng-click="setActive('cw')">Connect Wise</a></li>
Directive
navigation.$inject = ['$modal', 'localStorageService', '$log']
function navigation($modal, localStorageService, $log) {
return {
restrict: 'EA',
templateUrl: '/common/directives/navigation/navigation.template.html',
link: function(scope, element, attrs) {
$scope.setActive = function(tab) {
scope.active = tab;
$log.debug(scope.active);
}
}
};
}
Upvotes: 0