2014-03-28 18 views
2

我有我的佈局以下基本的細分:AngularJS - 如何使SPA具有多個部分

<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內顯示它們。

回答

1

爲了做到這樣的要求(沒有任何額外的插件),你必須將你的左視圖和右視圖放到他們自己的視圖中,並將每個路由的主視圖設置爲包括左,內容和右。

實施例:

<!-- 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.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"; 
    } 
}); 

路線/視圖2,它的主視圖(稱之爲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的更改都將在所有控制器/視圖中正確更新。

相關問題