我正在尝试编写一个装饰器,它将位于<ul>
元素上并应用&#34;活动&#34;根据当前活动的路径将类编辑到其子<li>
。
我是否可以将路由器注入装饰器并执行以下操作?
class ActiveNavDecorator {
RouteProvider _router;
String _currentRoute;
ActiveNavDecorator(this._router) {
_currentRoute = _router.currentURLPath() // I am looking for something that will do this
}
}
有谁知道我怎么能做到这一点?
谢谢,
震动
答案 0 :(得分:0)
这是我解决这个问题的方法。
我只能得到部分功劳,因为我几个月前研究了这个问题,并遇到了一个类似的解决方案,我的解决方案基于此。我不记得是谁写了原始解决方案或我在哪里阅读它,所以...提前道歉!如果原作者看到这个并发表评论,我会用归属更新我的答案。
无论如何,第一部分是装饰者:
import 'dart:html';
import 'package:angular/angular.dart';
import 'package:route_hierarchical/client.dart';
/// This decorator modifies UI elements based on the currently selected route.
///
/// For example, when a menu item is clicked, we add an 'active' CSS class
/// to that element so that the user can see where they are.
@Decorator(selector: '[current-route]')
class CurrentRoute {
Router router;
Element element;
/// Constructor.
///
/// Takes an HTML [element] to monitor and the application's [router]. The
/// element must contain a child <a> element. When the route changes, the
/// anchor href's first path component will be compared to the new route's
/// first path component. If it matches, the CSS class `active` will be
/// added to the element. If the route does not match, then the CSS class
/// `active` will be removed.
CurrentRoute(Element element, Router router) {
this.element = element;
this.router = router;
toggleActive(window.location.href);
router.onRouteStart.listen((e) {
toggleActive(e.uri);
});
}
/// Returns true if the given URI matches the anchor href for this element.
bool isRoute(String uri) {
Element anchor;
if (this.element is AnchorElement) {
anchor = this.element;
} else {
anchor = this.element.querySelector('a');
}
String anchorPath = anchor.pathname.split('/')[1];
String routePath = Uri.parse(uri).path.split('/')[1];
return anchorPath == routePath;
}
/// Set the `active` CSS class on an element when it matches the currently
/// selected route.
void toggleActive(String uri) {
if (isRoute(uri)) {
element.classes.add('active');
} else {
element.classes.remove('active');
}
}
}
基本机制是每次新路由开始时,用current-route
修饰的每个元素都将运行isRoute()
逻辑,该逻辑检查当前{{1}的第一个路径组件。 1}}等于锚点window.location
的第一个路径组件。 (例如,href
是/ foo / bar / baz,锚点window.location
是href
,那就是匹配。)
当然,还有其他可能的方法来执行此步骤,您应根据用例的需要自定义
/foo
。这恰好适用于我的用例。
接下来,您需要向Angular的DI注册isRoute()
。这是留给读者的练习。
最后,这是一个使用它的标记示例,基于Bootstrap样式导航:
CurrentRoute
请注意,装饰器应用于需要<ul class='nav navbar-nav'>
<li current-route>
<a href='/foo'>Foo</a>
</li>
<li current-route>
<a href='/bar'>Bar</a>
</li>
<li current-route>
<a href='/baz'>Baz</a>
</li>
</ul>
类的元素。如果元素本身不是锚点,装饰器将搜索该元素的第一个active
子元素。