Controllers in AngularJS and templates - javascript

I'm fairly new to AngularJS and I want to have the best practices from start. I want to know where should I put which controller I'll be using for a specific template. For now I've used this two:
In the html of the template
<div ng-controller="ImageManagerController"> </div>
In my routes.js
.state('home',{
url : '/',
templateUrl : '/src/images/views/home.html',
controller : 'ImageManagerController'
})
Is one of them better than the other?
Thanks for your time!

When you do both you will create 2 instances of the controller, you don't want that
The biggest advantage of setting it in the routing config is that any related resolve will be made available for injection in the controller that is referenced.
Also when you have a lot of routes it is easy to look up which controller you would need to modify for any specific route when they are all listed in a config

Using ng-controller directive in HTML :
This scopes the controller to a specific element on the page/template. That can make the code easier to read when you need multiple controllers on a single page and it allows the controller to be more specifically scoped.
New $scope object will created on ng-controller.
visible with page source or inspect element.
Controller in Route :
Allows you to specify a single controller for a template. Since this is part of the routing it makes it easy to find the controller that goes with the page. I use this to store and load overall page logic rather than element specific logic.
New $scope object is created per route on the ng-view.
Not visible with page source or inspect element.
If you will use this <div ng-view ng-controller="ImageManagerController"> then you'd need to change that controller as the route changed. So basically the router does that for you, and uses the controller you specified when you defined your routes.
I hope these differences will help you in deciding which to use.

Related

ng-app or angular.bootstrap

I was thinking when it would be best to not use the ng-App directive and instead go for angular.bootstrap. I understand from documentation what ng-App directive does and how it helps in telling compiler to set root of compilation. So my question is as to why I should use angular.bootstrap? What do they mean by saying in documentation that "If you need to have more control over the initialization process, you can use a manual bootstrapping method instead" documentation. Then I would also like to know as to for the solution that I am thinking for my application. I have one index.html file with one ng-app directive. Now for my application, I have different APIs, lets say for admin, students and instructors. So this is what I was thinking.Have the following files:
index.html
admin.js
students.js
instructors.js
I will have controllers for all of them and separate moduels, which will get the data from those APIs. Each div that will display the data from those controllers will be associated with the specific module, using angular.bootstrap and index.html will not have the ng-App directive. Is this the right approach ? Should I be just using ng-App and multiple controllers and a single module? Any help in understanding this is appreciated. Thank You.
One guideline that might help you is that you can only use ng-app once, but you can use angular.bootstrap multiple times
"If you need to have more control over the initialization process, you can use a manual bootstrapping method instead"
This means that with ng-app whenever directive is encountered bootstrapping will start automatically.
But with manual bootstrapping we can control it, say we want some data to be loaded first, to check for something defined or not or even as normally we do with checking of DOM ready event.

Can I link an external javascript file to an AngularJS controller?

This may be a dumb question. I know AngularJS controllers use javascript code to keep the application logic outside of the view. But I was wondering if I could link an external javascript file to a controller so it didn't have to be so long.
If it is possible would you also share the syntax of how I would do this. Something like:
app.controller('demoCtrl', ['$scope', function ($scope) {
$scope.msgtxt='Hello World';
src=somejavascriptfile.js;
}]);
If your issue is that the controller logic is too long, you are correct that it is a code smell. You want to make the controller as thin as possible, just enough logic to handle the view events and updating the model (scope). If you want to refactor your controller code, the first step is to extract out the logic into service(s) (in angular lingo providers / factories / services). The services can then be injected into your controller, similar to how you have injected the $scope service.
Read this sitepoint article for details on how to do this.
The next step might be look for logic (mainly UI related) which can extracted into directives.
In case you need to use an external javascript library within your angular application, the optimal way is to add that script to the scripts section of your html file, and wrap the functionality in a service or a directive (if it is UI related). Make sure to check if there are angular modules available out there for the 3rd party library you want to pull in.
Not only you can split your controller code among different files, but you probably should do that. An angular controller is responsible for the business logic behind a view, and only for that. You are doing it wrong if, inside the controller, you are (list not exhaustive) :
accessing your backend from it
manipulating the DOM
writing utility code for showing alerts in your application (for example)
Your components should be concise and of a single responsibility.
Here follows an example of how you would export some part of your code in a service. You do not link a js file from a controller, but you load it in your page, and inject the service as an argument of your controller :
1) Load your service in index.html :
<script src="js/factories/loggerService.js"></script>
2) Implement your service in loggerService.js
app.factories('loggerService', function () {
//
// Implement here some logging methods
//
// IMPORTANT: do not bloat this service with methods not related
// with logging
//
});
3) Inject your service in your controller :
app.controller('demoCtrl', function ($scope, loggerService) {
loggerService.info(...)
});
By the way, this loggerService would be useful only if you need something different than the service provided by angular built-in service $log
In a different file, define a service containing the logic and just call it from the controller.
app.controller('demoCtrl', ['$scope', function (ServiceFromDifferentFile, $scope) {
$scope.msgtxt='Hello World';
ServiceFromDifferentFile.doStuff()
}]);

EmberJS multiple controllers on one page

Is it possible to have multiple controllers on one route / page. I want to show 2 features of my application on one page. But they are not directly related so each would need it's own controller, model and (partial) view.
But I can't seem to figure out how I could do this.
It seems that I must use the {{render}} option here.
Is it possible to have a subdirectory structure here?
When I have {{render "dashboard.users"}} for the template it does look in template/dashboard/users.hbs but for the controller I can't seem to find where it looks and what the naming conventions should be.
E.g. should it be
App.DashboardUsersController = ... ?
edit:
Looks like it should be, but I shouldn't place it in a subfolder of controllers but name it dashboard_users_controller.js
You get this effect by rendering templates into multiple outlets of their parent template: Guide and API Docs
Here is a running JSBin demonstrating it

Angular.js load, process and display dynamic template obtained via REST $resource

I have an Angular app that needs to support customizable reporting. My intention is to allow the user to select one of many reports available and have a back end REST api provide the template and the data as JSON (end user can customize the template).
The app would then insert the template somehow into a "reporting" view page then put the data in the scope and Angular should compile and display the report / template.
I've looked into ng-include however that seems to support only an URL or path to a document, however I have the template text already via the REST service and I cannot use static urls or file paths, this needs to be via REST api, if ng-include accepted the template text directly that might work but it doesn't.
I've tried writing a directive, trying to call a method on the page (getTemplate()) that would load the template already fetched from the scope however my directive doesn't have access to the scope apparently.
What tactic should I use to accomplish this? A directive seems best but I'm obviously doing it wrong and completely lost in the docs and my many attempts trying to accomplish this.
You could compile the dynamic template to an element on the DOM in a controller and then in the controller have something like this:
var el = angular.element('#myselector');
el.html(mydynamichtmlfromresource);
$compile(el.contents())($scope);
I would setup your route with template with single DIV container (you could pull all the static container template in a single JavaScript file using HTMLToJS online tool or grunt task):
<section class="view">
<div id="myselector"></div>
</section>
I've tried writing a directive, trying to call a method on the page
(getTemplate()) that would load the template already fetched from the
scope however my directive doesn't have access to the scope
apparently.
Yes you are right, but there is a way to pass data from scope to directive. lets say you want to pass a var "x" from scope to directive
use this
<directive directiveVar='x'/>
inside directive, you need to use isolated scope
"scope": {
"directiveVar": "="
},
this variable will be available only in controller and postlink function, so your directive template needs to be like this
<ng-bind-html="directiveVar"/>
inside the postlink you may need to use this code snippet
$scope.directiveVar =$sce.trustAsHtml($scope.directiveVar)
References
http://docs.angularjs.org/api/ng.directive:ngBindHtml
http://docs.angularjs.org/api/ng.$compile

Angular sub-views

I google a bit about the topic but I couldn't get a clear answer on the subject, so apologies if this seems a pretty beaten down question. I've started with Angular not long ago, and I really want to be on the good path.
The application is bootstraped by app.js which defines the routes in the configuration. The index.html has a body with a ng-app directive an just a div inside with a ng-view.
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainController'
})
.otherwise({
redirectTo: '/'
});
This main.html and controller are the bulk of the app, which is quite simple.
Now I wanted to have a header, which either shows Login or the information from the user. I though that should be another Controller and another View, since the header should encapsulate all that code instead of polluting the main view.
What should I do?
I could remove the ng-app and create two different controllers for the header and the main app, but then I don't know how to associate each view to each ng-controller like the routeProvider is doing, although if I don't mind writing all the html inline, this should work. I would also lose routing which I don't really want to.
I could just create a ng-controller=headerController inside the app and still have the code inline. Is there an option to associate a template with a controller without the route definition?
What I'm currently going to do until I have a better option is to add all of this logic to the mainController. I just feel that I'm building big blocks instead of small ones that I can just compose. Imagine I do three more routes that need a header. Using option 1) or 2) I would have to write the template html for the header again in those views.
I would appreciate any links or help for this matter, I'm really curious how to approach this in a module fashion.
Thank you in advance.
I could remove the ng-app and create two different controllers for the header and the main app, but then I don't know how to associate each view to each ng-controller like the routeProvider is doing, although if I don't mind writing all the html inline, this should work. I would also lose routing which I don't really want to.
You will just write two different modules which have the same routeConfig and things will probably work. However, I do not think that it is the best solution in this case.
To answer your second question:
I could just create a ng-controller=headerController inside the app and still have the code inline. Is there an option to associate a template with a controller without the route definition?
You can use ng-include to include the template:
<body ng-app="MyApp">
<section ng-include="'header.html'" ng-controller="HeaderController"></section>
<ng-view></ng-view>
</body>
Moreover, you can keep the template inline by using either the $templateCache or by using <script> tag.
You can use ng-include to insert your template. I personally like to use ui-router

Categories

Resources