I'm currently developing an AngularJS application, and I've come across this one "issue" or I'd rather call it a "snag", that I'm not sure how to structure.
Would you create a different controller for a details views?
Let's say I'm creating a blog. The blog has some posts, and the first thing you'll see is the front page, showing the many posts that I've created. For this I would create a BlogController
, just like this:
(function () {
"use strict";
angular.module("BlogApp")
.controller("BlogController", ["$rootScope", "$scope", "PostService", function ($rootScope, $scope, PostService) {
$scope.blogPosts = [];
PostService.getBlogPosts()
.then(function success(response){
// Success!
$scope.blogPosts = response.data;
}, function error(err){
// Error!
});
}])
})()
This is a very basic controller that just gets all my blog posts. Whenever I click a blog post, I'd like to navigate to another view, showing the details of this post. I could create a separate controller for this, but as my BlogController
doesn't have much in it, I thought that I might as well just use this controller. I could do some actions based on the URL, like this:
(function () {
"use strict";
angular.module("BlogApp")
.controller("BlogController", ["$rootScope", "$scope", "PostService", "$location", function ($rootScope, $scope, PostService, $location) {
$scope.blogPosts = [];
var url = $location.url();
switch(url){
case "/blog":
PostService.getBlogPosts()
.then(function success(response){
// Success!
$scope.blogPosts = response.data;
}, function error(err){
// Error!
});
break;
case "/post-details":
// Do something specific for this post, if even anything needs to be done
break;
}
}])
})()
QUESTION
What is the most "correct" way of doing this? Perhaps "correct" is the wrong word, but I'd like to hear some argument for both methods. What would you do? Would you create a separate controller for the details?