Passing dependencies to a module angular - javascript

So I am somewhat new to angular, but not javascript. I am working with an app someone else wrote and am trying to create a new controller in an existing module. The controllers are almost identical to each other as far as dependencies go. The question I have is how do I pass the same dependencies to both controllers? It seems like you would be able to pass them in like this:
`angular.module('ApertureForm', ['dialogs.main','dialogs.default-translations','ui.bootstrap'])`
When I do that for both modules, the controller returns undefined for whatever reason. Thats where I get stuck. How do you pass in dependencies such as the above code? Any advice would be great.

angular.module('ApertureForm', ['dialogs.main','dialogs.default-translations','ui.bootstrap']) tells AngularJS to initialize an Angular module named ApertureForm and also load other Angular modules as dependencies for the module.
To add dependencies to a controller, you do something like the following:
angular.module('ApertureForm').controller('ControllerName', function($scope, $location, $timeout) {...});
angular.module('ApertureForm') = Get the module named ApertureForm.
Then create a controller called ControllerName. The closure is where you inject dependencies.
To prevent a controller's dependencies from getting renamed on minification, you can do:
angular
.module('ApertureForm')
.controller('ControllerName', ControllerName);
ControllerName.$inject = ['$scope', '$location', '$timeout'];
function ControllerName($scope, $location, $timeout) {...}
Docs: https://docs.angularjs.org/guide/di

In angular.module('ApertureForm',[ you list the modules you want to inject to your module. You list in once for each module you have. If You want to create a controller in one of your modules, then your can use:
var myApp = angular.module('ApertureForm');
myApp.controller('GreetingController', ['$scope', function($scope) {
$scope.greeting = 'Hola!';
}]);
$scope here is a dependency for controller
You can read more about it here

AngularJS Controllers and Dependency Injection:
angular
.module('ApertureForm', ['dialogs.main','dialogs.default-translations','ui.bootstrap'])
.controller('FormController', ['$scope', '$http', function($scope, $http) {
// FormController code...
}])
.controller('WebinarController', ['$scope', '$http', function($scope, $http) {
// WebinarController code...
}]);

Thanks to everyone for the help! All of it was very useful in learning the structure of angular and how to properly use the framework. #Yosvel Quintero was able to explain how the module works and why I was getting the error. When dependencies are passed into the module, not the controller, they are available to all controllers as it the module it's self is now aware of the dependencies, which is why I kept getting errors trying to pass them again. Hopefully the answers given in response to the question can help someone learn angular as well. Thanks guys!

Related

Where can I define an injectable object so that it's available in all controllers and directives?

Similar to this question: How to create separate AngularJS controller files?
I have a module that has controllers in several files, including controllers that are linked to directives. Where can I declare a factory such that it can be injected into all of them easily?
For example, in app.js I define the app level module
var app = angular.module('myApp', ['ngRoute']);
I would then expect to be able to define a factory in app.js like
app.factory('myFactory', function() { return { myThing: myThing}; });
And then be able to inject it into a controller that looked like
angular.module('myApp')
.controller('Ctrl1', ['$scope', '$http', 'myFactory',
function ($scope, $http, myFactory) {}]);
But I get the error Error: [$injector:unpr] Unknown provider:
Is there a way to do this?

How to refactor angular dependency injection for concatination and minification?

I have written my angular application into seperate files for my readability and ways to easily find things to edit/code. This is my app.js that requires the dependencies.
app.js
var app = angular.module('app', ['ngResource', 'ngRoute', 'app.services', 'app.controllers', 'app.feed','app.directives', 'app.factories']);
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
...
}]);
This is an example of how the dependencies are written out.
services.js
var app = angular.module('app.services', []);
app.factory('AuthService', ['$scope'], function($scope) {
...
}]);
However, when I try to concat the scripts, app is redefined constantly. I thought of taking out the var declaration but, I like to keep the files separate.
How would I be able to write this out where the dependency injections stay intact for my app.js, while still keeping the files separate.
To prevent the constant re declaration of you app variable, you can take advantage of the module pattern: Angular Style Guide:Modules.
Instead of explicitly declaring app in every dependency:
var app = angular.module('app.services', []);
app.factory('AuthService', ['$scope'], function($scope) {
...
}]);
You can define you service, component, directive, controller, etc as a part of the correct module:
angular.module('app.services')
.factory('AuthService', ['$scope'], function($scope) {
...
}]);
Declaring an 'app.services' module would only need to happen once.
See : Angular Style Guide:Modules for better explanations.

Should AngularJS modules be in their own file?

Fairly simple question, I can't seem to find a definitive answer. At the minute I've my module declared in one file :
var module = angular.module("app", ["agGrid", "ngAnimate", "ngSanitize", "ui.bootstrap"]);
and my controller in another :
angular.module("app").controller("mainCtrl", ["$scope", "$timeout", "dateFilter", "$http", "shareDataService", "getDataService", function ($scope, $timeout, dateFilter, $http, shareDataService, getDataService) {
Is this good structure or a waste of time and space?
Single Responsibility
Define 1 component per file.
The following example defines the app module and its dependencies, defines a controller, and defines a factory all in the same file.
Avoid this
angular
.module('app', ['ngRoute'])
.controller('SomeController', SomeController)
.factory('someFactory', someFactory);
function SomeController() { }
function someFactory() { }
The same components are now separated into their own files.
Do this
// app.module.js
angular
.module('app', ['ngRoute']);
// some.controller.js
angular
.module('app')
.controller('SomeController', SomeController);
function SomeController() { }
// someFactory.js
angular
.module('app')
.factory('someFactory', someFactory);
function someFactory() { }
https://github.com/johnpapa/angular-styleguide#style-y001
It's a good practice to keep them separate. This way, you don't end up mixing the module(s) definition and controllers / services / directives.
here you get some of the best practices in angular js -
Instead of slicing your app across horizontals that can't be broken
up, group your code into related bundles. This way if you remove a
module, your app still works.
https://github.com/angular/angular.js/wiki/Best-Practices
Having separate files for each type of component is ideal. I follow the structure in development:
app.js //where the module resides
routes.js //consists of routes
controllers/
services/
factories/
filters/
directives/
Define your module:
var app = angular.module();
Then use 'app' to declare other nested js in separate files, example:
app.directive()
However, in production, it is preferable to use task runner (eg gulp) to combine all the files and minify the final file.

How to define controllers in multiple files - AngularJs

I am trying to define controllers in separate files, but I'm getting the error:
transactionsController not a function got undefined
File structure
I have added files in this sequence
1- common.js
2- transactions.js
Common.js
In common files I have defined
var app = angular.module("spModule", ["ngMessages", "ui.bootstrap"]);
Transactions.js
angular.module('spModule').controller('transactionsController',
['$scope', '$http', function ($scope, $http) {} ]
);
HTML FIle
<body ng-app="spModule" ng-controller="transactionsController">
First, you should get rid of the global app variable. This is not necessary. Second, you have to understand the principle of the angular.module() method.
Using angular.module() with two parameters (e.g. angular.module('my-module', [])) would result in setting a new module with its corresponding dependencies. In contrast, when using angular.module('my-module') the corresponding module is looked up internally and returned to the caller (getting).
The means when you first define you application you might just create the following files and structure.
app.js
angular.module('myApp', []);
FirstController.js
angular.module('myApp').controller('FirstController', function () {});
SecondController.js
angular.module('myApp').controller('SecondController', function () {});
If you now include these files in your html document in this particularly order (at least app.js has to come first), your application works just fine with two separate controllers in two separate files.
Further readings
I can recommend the AngularJS Styleguide on modules for getting more ideas on this topic.
You Can put this controller in seprate file like mycontroller1.js
app.controller('myController', ['$scope',function($scope)
{
$scope.myValue='hello World'
}])
Same like this you can create new js file 'myNewcontroller.js' and can put new controller :
app.controller('myController2', ['$scope',function($scope)
{
$scope.myValue='hello World'
}])
Hope this will help you :) Cheers !!
You can do this stuff by creating modules. Create module and respective controllers. And inject that module to the main app module.
Transactions.js
(function() {
'use strict';
angular.module('tmodule', []);
})();
(function() {
'use strict';
angular.module('tmodule').controller('transactionsController', ['$scope', '$http',
function ($scope, $http){
}]);
})();
Now inject the "tmodule" to your Common.js file-
var app = angular.module("spModule", ["ngMessages", "ui.bootstrap","tmodule"]);
Load your common.js first. Move ng-app directive to <html> tag. Change transaction.js to:
app.controller('transactionsController', TransactionsController)
TransactionsController.$inject = ['$scope','$http']
function TransactionsController($scope, $http) {
};
Just for fun. Let me know what happens.

Angular JS Dependency Injection - Best Practice

I recently started working on my first Angular JS project, and I want to make sure I'm handling Multiple dependance injection correctly. Any suggestions or feed back will be greatly appreciated!
var app = angular.module('app', [
'ngRoute',
'ngIdle',
'ui.bootstrap'
]);
app.controller('testCtrl', [
'$scope', '$http', '$timeout', '$location', 'SessionService',
function($scope, $http, $timeout, $location, SessionService) {
// Do Stuff
}]);
I imagine you're just wondering about syntax here, There are a few different ways:
MyAppModule.controller("MyCtrl",MyCtrl);
MyCtrl.$inject = ['$scope', '$http', '$timeout', '$location', 'SessionService'];
function MyCtrl($scope, $http, $timeout, $location, SessionService){
//..do stuff
}
I like this way because it is pretty decoupled, and can be separated easily from angular,
wrapped up in a !function(){}() will keep it out of the global space.
This way is also the least work for the injector initialization.
Then there is the array syntax you have shown. That's nice if you like brackets (}])).
You can also forgo manually writing the string names and use a build tool like ngmin. Though you'd have to follow the guidelines for declaring your dependencies.
I wouldn't say there are any certain best practices associated with any of this, but its more of a preference.

Categories

Resources