Route match directive
So one directive that I need to write down because it keeps rolling around in my head is a route-matching directive for navigation highlighting.
It would come in handy when people use tabs or need to simply highlight the current page in a navigation bar.
Perhaps something like
<li ui-route="#/somepage/*">
<li ui-route="index.html">
<li ui-route="details.html#/tab1">
<li ui-route="/tab{{ $index + 1 }}">
And other such nonsense. It would simply add some sort of 'active' class and we could continue to expand the syntax support yet still try to keep it simple (regex may be too powerful?)
Should also probably have a better directive name than 'route'
Nice simple idea.
Yeh, +1 We could use it for bootstrap as well.
Does this just toggle a class or do we do more with it?
Right now I am just using ng-switch on $routeParams, so yeah, this would be definately helpful.
Okay so you want more than just a simple class being toggled?
@capaj What does your switch look like? I don't know how this is directly related
Maybe it should be a rootscope method for the most flexibility?
ng-class=" { active : match( '/someRoute' ) } "
Currently I am using something like,
$scope.$watch('$location.path()', function (path) {
$scope.activeNavId = path || '/';
});
/**
* getClass compares the current url with the id.
* If the current url starts with the id it returns 'active'
* otherwise it will return '' an empty string. E.g.
*
* // current url is '/products/1'
* getClass('/products'); // returns 'active'
* getClass('/orders'); // returns ''
*/
$scope.getClass = function (id) {
return ($scope.activeNavId.substring(0, id.length) === id) ? 'active': '';
};
with bs markup
<ul class="nav nav-tabs nav-stacked">
<li ng-class="'getClass(/page/edit)'">
<a ng-href="/pages/edit/page.id">Page Details</a>
</li>
</ul>
Problems that I am facing with this approach
- If i have a path like '/pages/:pageid/details' & '/pages/:pageid/campaigns', then something like ng-class="'getClass(/pages/{{page.id}}/details)'" doesnt seem to work.
- Too noisy as I have to specify route both in li tag and in ng-href
So I propose something like
<li ng-class="{'active': routeActive}" ui-route>
<a ng-href="/pages/:pageid/detalis">some link</a>
<li>
Default behavior of ui-route could be
- Check expression on uiRoute, ng-href & href attrs on the same element & use it as route path
- If not found, traverse/transclude child nodes & use the first ng-href/href value as route path.
If route path matches with activeNavId, then we set routeActive to true, which can be used with ng-class expression.
Additionally, having ability to match route paths like ui-route="/pages/:pageid/detalis" would be handy as well :)
What do you guys think?
I think there is too much disconnect between the href or ng-href property and the current DOM element to make that sort of assumption.
I will agree with you that it's tediously verbose to have to declare the route twice, but unlike client-side frameworks I don't know of any better solution.
I also think that if we do a $scope function, it should simply return a boolean, but I like your idea of ui-route merely adding some sort of $routeActive boolean onto the scope. This would also be more efficient overhead-wise.
I would say lets compromise, you can specify a route OR it will TRY to find an href or ng-href property. But having it go into children elements to retrieve these properties seems detrimental to me (and a risk for breakage due to compiling/rendering order).
This would mean you can do:
<a ui-route href="/pages" ng-class="{active:$routeActive}">Pages</a>
OR you can do:
<li ui-route="/pages" ng-class="{active:$routeActive}">
<a href="/pages">Pages</a>
</li>
Thoughts?
Also, what should we support? Simple route definitions Simple route definitions + additional features (such as optional parts, etc) Full-blown regex?
Even I wasnt fully convinced about traversing child elements as risk of breakage is very high :(
How about something like
<li ui-route="thisPath='/pages'" ng-class="{active:$routeActive}">
<a ng-href="thisPath">Pages</a>
</li>
where ui-route takes an expression
- if the expression is just a string, then we check for match & update $routeActive boolean
- if it is an assignment expression, then that variable can be added to the child scope with the url path
I think angular already does this magic of creating a scope var when an expression is parsed.
If we can make the above syntax work, then I feel route definitions or regex's parsing will be redundant as we can fully parse the expression like
<a ui-route="/pages/{{pageId}}/new" ng-class="{active:$routeActive}">New Page</a>
or
<li ui-route="uri='/pages/{{pageId}}/new'" ng-class="{active:$routeActive}">
<a ng-href="uri">New Page</a>
</li>
Assuming pageId is in scope, then /pages/{{pageId}}/new will evaluate to /pages/wwe33233ws/new, which can be directly matched against $location.path()
I am not sure if there are any other use cases where regex or route definitions will be required.
What do you think?
Actually my version of ui-route handles observance AND does regex.
So you can do:
thisPath = '/pages'
…
<li ui-route="{{thisPath}}"><a ng-href="{{thisPath}}">
Or you can do:
<li ng-repeat="tab in tabs" ui-route="/{{tab}}/[0-1]*">
I pushed some modifications in accordance with the new approach, but once again I'm having difficulty getting tests to pass.
Small note..
- uiConfig is not used and can be removed
- on line 22, shouldnt it be new RegExp('^' + newVal + '$', ["i"]);
Also I am not able to assign the expresssion to local var ui-route="thisPath='/pages'"
do we need to parse & apply ??
angular.module('ui.directives').directive('uiRoute', ['$location', '$parse', function ($location, $parse) {
return {
restrict: 'AC',
priority: 100, // must occur before attrs.ngHref is removed
link: function ($scope, elm, attrs) {
var watcher = angular.noop;
// Used by href and ngHref
function observeHref(newVal) {
watcher = function watchHref() {
$scope.$routeActive = ($location.path().indexOf(newVal) > -1);
};
watcher();
}
attrs.$observe('uiRoute', function(newVal) {
if(!newVal) return;
if(newVal.indexOf('=') !== -1) {
var mdl = newVal.split('=')[0]
, pathGetter = $parse(newVal);
$scope[mdl] = newVal = pathGetter(mdl);
}
watcher = function watchRegex() {
var regexp = new RegExp('^' + newVal + '$', ["i"]);
$scope.$routeActive = regexp.test($location.path());
};
watcher();
});
if (attrs.ngHref) {
// Setup watcher() every time ngHref changes
attrs.$observe('ngHref', observeHref);
} else if (attrs.href) {
// Setup watcher()
observeHref(attrs.href);
} else {
throw new Error('uiRoute missing a route or href property on ' + elm[0]);
}
$scope.$on('$routeChangeSuccess', function(){
watcher();
});
}
};
}]);
This works, but its bit ugly. Is there a better way to parse this expression ui-route="thisPath='/pages'" ?
Changed. Still have failing tests :/
No I'm not coding it the way you originally suggested. It's not a good use-case. You should not be doing an expression or executing anything. It should be read-only properties. If you MUST assign something inline like that use ng-init instead. Although for the same reason you should avoid ng-init, you shouldn't really assign value in the view too much.
Although if you MUST do the same thing, nothing stops you from doing ui-route="{{thisPath='/pages'}}"
Yep..examples in the docs http://docs.angularjs.org/api/ng.directive:ngClick spoiled me :)
ui-route="{{thisPath='/pages/{{id}}'}}
will this work. If not, is there any other way tat I can assign the value to a scope var? hmm..i need to experment a bit on this.
you have to remind yourself that everything in between {{}} is just javascript.
ui-route="{{thisPath='/pages/'+id}}
ng-click is different. This is an interaction that you are triggering, so setting a value makes sense here. But ui-route is not an event that is triggered or some interaction. It is merely a way to render the view, so it is read-only.
Yep makes sense. My initial usecase was specific to BS markup, where we have 'active' class is set on li corresponding to href on child link. Good to know that ui-route="{{thisPath='/pages/'+id}} works.