AngularJS - 如何使用多个部分制作SPA

时间:2014-03-28 04:09:56

标签: angularjs templates routes

我的布局有以下基本细分:

<body>
   <div id="left"></div>
   <div id="content" ng-view></div>
   <div id="right"></div>
<body>

我在主要内容中使用ng-view通过$routeProvidertemplateUrl动态加载内容。但是,#left#right中的内容有时需要根据我转到的页面进行更改。

动态添加/删除元素到#left#right的最佳方法是什么?我基本上希望如果我使用控制器/view1加载View1Controller,那么如果此视图有额外的组件,那么我可以在View1Controller中显示它们。

2 个答案:

答案 0 :(得分:1)

我不完全理解你的要求,但是你从angular-ui看了一下ui-router。链接:http://angular-ui.github.io/ui-router/

顺便说一下,你可以在这里看到示例应用程序:http://angular-ui.github.io/ui-router/sample/#/希望它有所帮助。

答案 1 :(得分:1)

为了达到这种要求(没有任何额外的插件),您必须将左右视图拉到自己的视图中,并将每个路径的主视图设置为包括左侧,内容和右侧。< / p>

示例:

<!-- Core Html-->
<body ng-app> 
  <div ng-controller="MainCtrl" ng-view></div>
</body>

<强> MainCtrl.js

angular.module('MyApp').controller('MainCtrl', function($scope){
  $scope.defaults = {
    leftView: "views/view1.html",
    rightView: "views/view2.html"
  }
});

路线/ view1及其主视图(称之为view1.html)

<div ng-controller="View1Ctrl">
  <div id="left" ng-include="defaults.leftView"></div>
  <div id="content" ng-include="contentView"></div>
  <div id="right" ng-include="defaults.rightView></div>
</div>

<强> View1Ctrl

angular.module('MyApp').controller('View1Ctrl', function($scope){
  $scope.contentView = "views/view1/firstPanel.html";

  //Add some other functions to change $scope.contentView to say 
  //"views/view1/secondPanel.html"
  //You could also temporarily replace $scope.defaults.leftView
  //and rightView to show the View1 route in full screen so to speak. like so
  $scope.setFullPanel = function(){
    $scope.defaults.leftView = ''; //or something else
    $scope.defaults.rightView = '';
    $scope.contentView = "views/view1/fullScreenPanel.html";
  }
});

路线/ view2及其主视图(称之为view2.html)

<div ng-controller="View2Ctrl">
  <div id="left" ng-include="defaults.leftView"></div>
  <div id="content" ng-include="contentView"></div>
  <div id="right" ng-include="defaults.rightView></div>
</div>

<强> View2Ctrl

angular.module('MyApp').controller('View2Ctrl', function($scope){
  $scope.contentView = "views/view2/firstPanel.html";

  //Add some other functions to change $scope.contentView to say
  //"views/view2/secondPanel.html"

});

现在您已经为默认的左侧和右侧面板设置了路线和视图,您可以为没有左右的面板设置路线,例如:

<div ng-controller="View3Ctrl">
  <div id="content" ng-include="contentView"></div>
</div>

<强> View3Ctrl

angular.module('MyApp').controller('View3Ctrl', function($scope){
  $scope.contentView = "views/view3/wholeScreenPanel.html";

});

希望这会有所帮助。另外,“scope hierarchy reasons”确保更高级别的“默认”变量保存在$ scope.defaults上非常重要,因此View1Ctrl或View2Ctrl到$ scope.defaults的任何更改都将在所有控制器/视图中正确更新。