Reputation: 441
I was wondering about the best way to structure an angular.js application. I believe that all directives download their respective templates via an ajax request. Therefore, is it better to enclose each distinct section of an SPA in a directive as an individual unit with its own template html and controller:
<html>
<head>
</head>
<body>
<section>
<directive1></directive1>
</section>
<section>
<directive2></directive2>
</section>
<section>
<directive3></directive3>
</section>
</body>
</html>
Or is it better to reserve directives for DOM manipulation and embed all controllers inside the main html page:
<html>
<head>
</head>
<body ng-app="myapp">
<section ng-controller="controller1">
...
</section>
<section ng-controller="controller2">
...
</section>
<section ng-controller="controller3">
...
</section>
</body>
</html>
I was wondering what the advantages and disadvantages of each approach are, in terms of performance, best practices etc. Thanks in advance.
Upvotes: 0
Views: 109
Reputation: 1519
I would recommend wholeheartedly for any greenfield project, that you should make every effort to avoid the use of ng-controller
in your application.
This will save alot of heartache if/when you attempt to upgrade any application to AngularJS version 2.0 whenever it is released. It is going be very different from current versions and one of those changes is that there will be no ng-controller
.
It has been found that they encourage developers to take short cuts and instead of designing modular loosely coupled components/directives, what we can end up with is a tightly coupled n-tier Controller hierarchy.
I found this to be a very good article with topics to consider given the declared direction of Angular 2.0
http://teropa.info/blog/2014/10/24/how-ive-improved-my-angular-apps-by-banning-ng-controller.html
It may be difficult at the start of a project to design directives where you would automatically reach for ng-controller
but I think that is the best approach in the longer term.
Given the huge number of Angular projects that have been undertaken in the last couple of years, there will be many conversations within organisations to assess whether they will ever be able to invest the effort required to move off 1.2-1.3 and essentially rewrite applications in order to be able to use 2.0.
Upvotes: 2
Reputation: 65
You're comparing apples to oranges. Controllers call services to retrieve the models and attach them to your $scope (in other words, they initialize scope). Directives are re-usable components that you can use in your views.
The two are not mutually exclusive: you can use controllers with directives, controllers without directives, and directives without controllers.
It is meaningless to compare them with regards to approach.
Upvotes: 1
Reputation:
Both approaches are almost same as both will be doing the same job.
Upvotes: 1