Skip to content

Commit e5fff72

Browse files
committed
fix(uiSrefActive): optionally match child states
This issue provides support for optionally counting a link as active if any of its child states are active and parameters match. Closes angular-ui#818
1 parent cf34271 commit e5fff72

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

src/stateDirectives.js

+9-1
Original file line numberDiff line numberDiff line change
@@ -147,13 +147,21 @@ function $StateActiveDirective($state, $stateParams, $interpolate) {
147147

148148
// Update route state
149149
function update() {
150-
if ($state.$current.self === state && matchesParams()) {
150+
if (isMatch()) {
151151
$element.addClass(activeClass);
152152
} else {
153153
$element.removeClass(activeClass);
154154
}
155155
}
156156

157+
function isMatch() {
158+
if (typeof $attrs.asParent !== 'undefined') {
159+
return $state.includes(state.name) && matchesParams();
160+
} else {
161+
return $state.$current.self === state && matchesParams();
162+
}
163+
}
164+
157165
function matchesParams() {
158166
return !params || equalForKeys(params, $stateParams);
159167
}

test/stateDirectivesSpec.js

+16
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,8 @@ describe('uiSrefActive', function() {
278278
url: '/:id',
279279
}).state('contacts.item.detail', {
280280
url: '/detail/:foo'
281+
}).state('contacts.item.edit', {
282+
url: '/edit'
281283
});
282284
}));
283285

@@ -316,6 +318,20 @@ describe('uiSrefActive', function() {
316318
expect(angular.element(template[0].querySelector('a')).attr('class')).toBe('');
317319
}));
318320

321+
it('should match child states when asParent attribute is used', inject(function($rootScope, $q, $compile, $state) {
322+
template = $compile('<div><a ui-sref="contacts.item({ id: 1 })" ui-sref-active="active" as-parent>Contacts</a></div>')($rootScope);
323+
$rootScope.$digest();
324+
var a = angular.element(template[0].getElementsByTagName('a')[0]);
325+
326+
$state.transitionTo('contacts.item.edit', { id: 1 });
327+
$q.flush();
328+
expect(a.attr('class')).toMatch(/active/);
329+
330+
$state.transitionTo('contacts.item.edit', { id: 4 });
331+
$q.flush();
332+
expect(a.attr('class')).not.toMatch(/active/);
333+
}));
334+
319335
it('should resolve relative state refs', inject(function($rootScope, $q, $compile, $state) {
320336
el = angular.element('<section><div ui-view></div></section>');
321337
template = $compile(el)($rootScope);

0 commit comments

Comments
 (0)