问题
I'm trying to generate the following single page app with UI that looks something like this:
On the left is a list of item images, and whenever an item is clicked the right side is populated with the item's details, larger image, etc - you've seen and know what I'm talking about. I'd also like to apply proper routing, such that when accessing #/item/:itemID
, the view will respond accordingly and the detailed item will be rendered. The items list should still be shown, without changing position (it's scrollable vertically).
As I'm quite new to angular, I'm still working out how to approach this. I'm thinking about using the same template and different controllers in my routes:
var app = angular.module('app', []);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'items.html' ,
controller: 'ItemsController'
}).when('/item/:itemID', {
templateUrl: 'items.html' ,
controller: 'ItemDetailsController'
}).otherwise({ redirectTo: '/' });
}]);
I'm assuming my template should include both sides of the view (list and details), the router should call the same controller, and the controller should check for the #/item/:itemID
route and render the details view if present. The actual items are fetched using $http
, and the item details are fetched when it is clicked (and then rendered).
I haven't used ngInclude
and ngView
enough to pick the correct tool set here, so I'd appreciate some input on how to proceed - thanks.
回答1:
There are dozens of ways to approach this, but if the app is fairly simple:
<!-- Static content here -->
<div ng-repeat="image in imageLinks">
<div (ul/li, whatever) href="/myRouting/{{image.id}}">{{image.image}}</div>
</div>
<-- End Static Content --->
<div class="middleContentWrapper">
<div ng-view ></div> <----your 'content area'
</div>
Or create a directive for the menu layer.
And, like the other answer says, one controller is enough for the partial views.
The actual items are fetched using $http, and the item details are fetched when it is clicked (and then rendered).
You are probably doing this anyway, but I would cache these items by plugging them in an array or object in your factory/service so you don't have to keep hitting the server...
回答2:
Using different controllers for same view or same partial view would be redundant. Instead your should simply use the same controller for both routes, like
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'items.html' ,
controller: 'ItemsController'
}).when('/item/:itemID', {
templateUrl: 'items.html' ,
controller: 'ItemsController'
}).otherwise({ redirectTo: '/' });
}]);
So when navigating to /
your
$selectedItem = null;
while /item/1
$selectedItem = Item.get({ id:$routeParams.itemId })
would load the details view with the items details.
来源:https://stackoverflow.com/questions/16859684/multi-part-view-with-routing-in-angular