I'm a bit new to Angularjs. I'm confused about multiple controllers. I know Angular app can have multiple controllers. But I'm confused when to use multiple controllers. What's the advantage of having multiple controllers? Can anyone help me to clarify this? Thanks
In order to modularize your application based on the feature wise, you can have multiple controllers.
For example if you have a login feature, you can have a separate controller which does the login part(Fetching data,checking the authentication etc)
var app = angular.module('app', []);
app.controller('LoginController', function ($scope) {
//Controller Code Here which fetches the API and check authentication
});
app.controller('ProductController', function ($scope) {
//Controller Code Here which loads the products
});
For different functions we need different controllers. For example if you need a ui modal to display something then for that modal you need different controller which will handle only modal's functionality. If you try to code everything in single controller then it will be confusing for you when in future you want to edit some contents of any html page.
Related
I have been working with AngularJs for a while and I now feel comfortable enough with it that I started to review my earlier work.
So I started out with following the basic tutorials and got used to setting up the application, controllers and services as following:
Module injections
// application.js
angular.module('appname',
[ // dependencies
'ui.router'
, 'someController'
]);
// somecontroller.js
angular.module('someController', [])
.controller('someCtrl',
['$scope', function ($scope) {
// Some stuff
}]);
And of course including js files in my index.html e.g.:
<script src="path/angular.js"></script>
<script src="path/angular-ui-router.min.js"></script>
<script src="path/application.js"></script>
<script src="path/somecontroller.js"></script>
Since I tend to separate all logic by feature (separate directory, own MV* structure per directory), I found that the list of dependencies can grow rather large. And also I think adding each controller, service etc. to the app dependencies is kind of a drag.
So I started to do it this way instead:
Single application
// application.js
var app = angular.module('appname',
[ // dependencies
'ui.router'
]);
// somecontroller.js
app.controller('someCtrl',
['$scope', function ($scope) {
// Some stuff
}]);
The obvious win for doing it like this is that I do not longer have to add the controller reference to the app dependencies.
So now my question(s) are:
Besides the obvious, what is the difference between the 2 methods?
From the Angular perspective which of the methods is considered
"good/bad practice"? And why?
I don't think the second method is good. You add all controllers to your app main's module. If you want to truly group your code by feature, I recommend a third approach :
// application.js
angular.module('appname',
[ 'ui.router'
, 'appname.booking'
]);
//booking.mod.js
angular.module('appname.booking', []);
//booking.ctrl.js
angular.module('appname.booking')
.controller('BookingCtrl', function ($scope) {
// Some booking logic
}]);
This way, you create a module per feature and obtain a project architecture easy to understand and navigate.
Looks like you need to read a bit more about modules.
The difference between your two approaches is that in the first one you create a different module for your controller and by injecting that module into the app dependencies you tell angular "by the way, I want the features that come with that module, too".
In your second approach, you only have a single huge module for the entire application, which means all the controllers, service, directives, .. will be automatically considered as part of the application.
Both approaches work, however having different modules for different functionality could help you structure you application better, as well as provide more reusability & easier testing.
In your first method you are creating different modules for your controller. That's why you have to inject your controller name at the time of creating Angular JS app.
angular.module('appName', ['controllerName']);
angular.module('controllerName', []);
In the second approach you are only creating a single app and you are attaching the controller to this app. In this case you don't have to inject the controller name at the time of creating the Angular JS app.
var app = angular.module('appName', []);
app.controller('controllerName', function(){});
About your second question, it depends on the type of application you are developing. For a small single page application a single app module will do fine
When working on large applications everything might not be contained on a single page, and by having features contained within modules it's much simpler to reuse modules across apps. So in this case your first approach is better.
You can create different modules like shown below and can inject to your app;
var sharedServicesModule = angular.module('sharedServices',[]);
sharedServices.service('NetworkService', function($http){});
var loginModule = angular.module('login',['sharedServices']);
loginModule.service('loginService', function(NetworkService){});
loginModule.controller('loginCtrl', function($scope, loginService){});
var app = angular.module('app', ['sharedServices', 'login']);
Anyone know the best recommended way of creating models in a separate JavaScript file and have these injected into the controllers that need them, rather than creating the models on fly normally in the controller?
This would make it so much easier to pass around the model and you would know exactly what you was passing around.
I have some thoughts on using Services, and inject these where I need i.e. controllers.
Controllers would then pass these onto specific services to do any heavy lifting to keep my controllers nice and light.
Is services the only and recommended way to go ? Or is there a better alternative way ?
Any use of third-party libraries / modules would also be considered.
I think services are the way to go. Not only are they injectable but they are also Singletons - meaning wherever they are injected, the same instance is shared.
Example of a service which uses the $http service to make an asynchronous call to retrieve data:
app.factory('customerService', function($http) {
var customers = [];
$http({ url: 'api/customers/all', method:'GET'}).success(function(data) {
angular.copy(data, customers);
});
return {
customers: customers
};
});
In your controller or directive, you can then inject the service and bind customers to your scope:
app.controller('ctrl', function($scope, customerService) {
$scope.customers = customerService.customers;
});
The best way to do it is by service for couple of reasons.
If you use ng-view and routing the service is not reloading and your data is safe in service
It's easy injectable to controllers
Provides two-way data binding between controllers
working plunker with two-way data binding between controllers
http://plnkr.co/edit/pt2xwlYqvY3r840tHJ92?p=preview
NOTE: if you don't have a dot in your model you are doing something wrong ;)
I believe services are the best way for this.
I have used scope inheritance to place some methods that most of my app would need at once such as a routing method I attached these to the .run () method of my main module/app.
You could separate your models into separate modules if you needed to structure your app that way.
I am building a web application with AngularJS and have built out a AngularJS Service that my controller uses to create, retrieve, update, delete data from. I want to farm out the UI work to another developer, but I don't want them to require the dependencies that the AngularJS Service does. I'd like to build a Mock Service and just return mock data rather than call the live REST service.
My App is set up like this:
var myApp = angular.module('myApp', ['ui.bootstrap']);
My Controller currently hooks up to the Service using:
myApp.controller('TodoCtrl', function TodoCtrl($scope, $JSOMService) {
$JSOMService.DoStuff();
});
And my Service is defined like this
myApp.service('$JSOMService', function ($q, $http) { ... });
What the are best ways to handle switching out the service for another one? This is a little different from Unit Testing and I wondered if there are any common ways of doing this?
For now I'm just having a slightly different code base where I just switch out the Angularjs Service javascript files loaded to handle this.
You can get access directly to the provider service, which controls injections. It would look something like this, where $provide is injected:
$provide.value('$JSOMService', MockJSOMService());
This will basically say, whenever someone asks for $JSOMService, give them whatever was returned from MockJSOMService.
You can set this up at the when you set up your app. Like this:
myApp.run(['$provide', function($provide) {
$provide.value('$JSOMService', MockJSOMService());
}]);
This is basically how you could switch out services. Admittedly a little funky, but I hope this helps!
Is there a way to refresh a controller from another controller?
For example, Controller1 runs then Controller2 runs. At the end of Controller2 there is a
"command" to re-run Controller1. Is this possible?
In my post I had made earlier it seems like my questions was unclear what I was trying to do. Here is a link to it.
Updating a controller from another controller Angular
if you are using ngRoute there is a method to re-run the all the controller without having to reload the page.
app.controller('MyCtrl', function($route){
$route.reload()
})
If you want to refresh data, please use services and refresh data in the services. Sequential things can be done of ajax by using promises. Please let me know if you need any help in designing the solution
I think you need to look into using directives. By using directives you can encapsulate and share scope objects.
Please read the documentation on directives and "shared scope".
http://docs.angularjs.org/guide/directive
I'm currently working on a Mobile WebApp built with AngularJS. The basic functionality is similar to a simple ToDo's app: Create a list of items (with ng-repeat) and mark those items as checked or delete them from the list. Checked items are being pushed into a seperate ng-repeat controller.
My current problem is: If you reload the page or close the app, the list contents are gone. I have to be able to store the data of my ng-repeat controllers to localStorage, IndexedDB, WebSQL, Cookies or whatever solution is the most elegant on mobile devices.
I know there are several solutions out there: There's the $cookies / $cookieStore module of the Angular API, there's a solution based on prestistence.js and so on. But I couldn't figure out wich solution is the best for mobile, cross device. I don't want to restrict the app to certain plattform, though I'm primary aiming at Firefox OS atm.
Thanks for any form of advice!
I recommend localStorage. The API is simple and widely supported.
If you'd like to store your data in the cloud I recommend using Firebase in conjunction with Angularfire. It will get you up and running in a matter of minutes.
First you include Firebase and AngularFire:
<script src="https://cdn.firebase.com/v0/firebase.js"></script>
<script src="angularFire.js" type="text/javascript"></script>
Then you declare firebase as a dependency for your angular app:
var myapp = angular.module('myapp', ['firebase']);
Now all you need to do is bind a Firebase URL to a model in your controller:
myapp.controller('MyCtrl', ['$scope', 'angularFire',
function MyCtrl($scope, angularFire) {
var url = 'https://MyFirebaseURL.firebaseio.com/foo';
$scope.foo = angularFire(url, $scope, 'foo');
}
]);