【问题标题】:AngularJs: stateful client-side routingAngularJs:有状态的客户端路由
【发布时间】:2012-11-18 14:04:30
【问题描述】:

这是我为提出这个问题而创建的演示以及所要求的内联代码: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'},
          ];

    }
  };
});​

这是我一直在开发的应用程序的一小部分,但它清楚地显示了它在做什么。页面中有导航菜单,菜单项是指向由初始化根控制器的 angular.js 路由处理的哈希的链接等,描述起来相当棘手,但代码示例清楚地表明了这一点。 每次单击导航菜单项时,都会重新呈现整个页面内容的问题 - 路由是无状态的,它对以前的状态一无所知。当用户只是在菜单项(或浏览器历史记录)之间导航时,我想通过重新使用导航菜单数据/模板呈现结果来避免这种情况。是否可以?我确定是的,只是想看看有人有没有好主意。谢谢!

更新: 我发现了一些可能对我有帮助的东西: http://www.bennadel.com/blog/2420-Mapping-AngularJS-Routes-Onto-URL-Parameters-And-Client-Side-Events.htm

【问题讨论】:

  • 我尝试在 JSFiddle 中单击侧边栏菜单,它似乎没有被重新渲染。而且,我尝试单击浏览器的“前进”“后退”历史按钮,它也可以正常工作。你解决了这个问题吗?还是您面临其他问题?
  • 重新渲染。观察设置断点 $scope.templateUrl = $scope.templateId + '.html';一行代码并开始导航。您将看到代码在每个项目单击/浏览器历史记录后停止在该行,并且页面在停止时刻为空,然后您继续执行页面重新呈现。

标签: javascript angularjs url-routing


【解决方案1】:

我会将导航菜单放在 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();
};

Fiddle

【讨论】:

    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2014-09-05
    • 2016-01-09
    • 2014-06-30
    • 2014-02-10
    • 2015-12-06
    相关资源
    最近更新 更多