[英]AngularJs: stateful client-side routing
这是我为询问此问题而创建的演示,以及按要求提供的内联代码: http : //jsfiddle.net/Gncja/1/
<script type='text/ng-template' id='root.html'>
<list template-id='sidebar.templateId' selected-item-id='sidebar.selectedItemId'></list>
</script>
<script type='text/ng-template' id='sidebar.html'>
<ul style='width:100%;' class='nav nav-list bs-docs-sidenav'>
<li ng-repeat='item in data' ng-class="{active:item.id==selectedItemId}">
<a ng-href='#/{{item.id}}'>
<i class=icon-chevron-right></i>
<span ng-bind='item.text'></span>
</a>
</li>
</ul>
</script>
<body ng-app='main'>
<div ng-view></div>
</body>
function RootCtrl($scope, $routeParams){
$scope.sidebar = {
templateId: 'sidebar',
selectedItemId: $routeParams.navItemId
};
}
RootCtrl.$inject = ['$scope','$routeParams'];
angular.module('main', []).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/:navItemId', {
templateUrl: 'root.html',
controller: RootCtrl
}).
otherwise({redirectTo: '/1'});
}]).
directive('list', function(){
return {
restrict: 'E',
replace: true,
scope:{
'templateId': '=',
'selectedItemId':'='
},
template:'<ng-include src="templateUrl"></ng-include>',
controller: function($scope, $element, $attrs){
$scope.templateUrl = $scope.templateId + '.html';
$scope.data = [
{'id':'1', text:'lorem ipsum'},
{'id':'2', text:'dolor sit amet'},
];
}
};
});
这只是我一直在研究的应用程序的一小部分,但清楚地显示了它在做什么。 页面中有导航菜单,菜单项是指向由hash.js路由处理的哈希的链接,该路由初始化了根控制器等,要描述起来非常棘手,但是代码示例清楚地显示了它。 每次单击导航菜单项时,都会重新呈现整个页面内容的问题-路由是无状态的,它对先前的状态一无所知。 我想通过在用户只是在菜单项(或浏览器历史记录)之间导航时重新使用导航菜单数据/模板呈现结果来避免这种情况。 可能吗? 我敢肯定,只是想看看某人是否有好主意。 谢谢!
更新:我发现了一些可能对我有帮助的东西: http : //www.bennadel.com/blog/2420-Mapping-AngularJS-Routes-Onto-URL-Parameters-And-Client-Side-Events.htm
我将导航菜单放在ng-view之外(因此它不会重新渲染),但是将ng-class与location.path()结合使用来区分当前选择的项目。 例如,
<div ng-controller="navCtrl">
<ul ...>
<li ng-repeat='item in navData' ng-class="{active:isActiveRoute(item.id)}">
...
</ul>
</div>
<div ng-view></div>
然后在navCtrl中:
$scope.navData = [
{'id':'1', text:'lorem ipsum'},
{'id':'2', text:'dolor sit amet'},
];
$scope.isActiveRoute = function(route) {
return '/' + route === $location.path();
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.