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.
Related
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!
I have a problem with Angular and injecting $cookies into a controller.
The $cookies is working fine in a service, but with this controller I'm getting an issue.
var app = angular.module('app', [
"ui.router",
"ngCookies",
'ui.bootstrap']);
angular
.module("app")
.controller("ListController", ListController);
ListController.$inject = ['$scope', 'DataService', '$state', "AuthenticationService", "$cookies"];
function ListController($scope, DataService, $state, AuthenticationService, $cookies) {
....
}
The $cookies object is coming through as undefined. The angular-cookies.js is included on the page, and is working inside the included AuthenticationService.
I found my problem:
Someone had cut and pasted the original controller code into a new controller, but neglected to rename the controller on the line:
ListController.$inject =[...];
So, when I came along and added the $cookies parameter, my version was being overridden.
Try this way
var app = angular.module('app', [
"ui.router",
"ngCookies",
'ui.bootstrap']);
angular
.module("app")
.controller("ListController",['$scope', 'DataService', '$state', "AuthenticationService", "$cookies", function ($scope, DataService, $state, AuthenticationService, $cookies) {
....
}]);
Did you include the file angular-cookies[.min].js ?
Also, as a good practice, don't use the same module for the app and the controllers. Have a
angular.module('app', [ 'app.controllers']);
angular.module('app.controllers', [
\\ define each controller here
]);
defined so that you can have clean separation of them.
Are $scope, DateService, $state available in your controller? I usually put this line of code after the declaration of controller
angular
.module("app")
.controller("ListController", ListController);
// <...loading all JS in one file by the Mincer library...>
angular
.module('firstapp', ['ngRoute', 'ngMaterial', 'ngMdIcons'])
.factory('MessagesService', ['$scope', '$filter', '$mdToast', '$animate', MessagesService])
.controller('MenuController', ['$scope', '$filter', '$location', 'MessagesService', MenuController]);
MessagesService is a function;
MenuController is a function;
I received a error: MessagesService is not exists.
If i remove MessagesService dependency from MenuController - it works good.
But i need create Message controller, what will add some toast about application, and dont know, how.
You could never inject $scope dependency inside angular factory
It should be without $scope dependency
.factory('MessagesService', ['$filter', '$mdToast', '$animate', MessagesService])
Is there a way to know what dependencies were injected into my Angular module?
angular.module('myModule', [
'ui.bootstrap'
])
.controller('myController', [function () {
// var dependencies = Magic.dependencies;
// console.log(dependencies);
}]);
In your controller, if you inject $window, you can dig for the dependencies, specifically, there exists a .requires on your module. To do this, you can either declare your module as a global var so we can find it on our $window, in this case, let's call it app - or - you can bypass globals and $window and call angular.module('myModule').requires directly.
I've added ngRoute as well to prove the array of dependencies that will be discoverable.
var app = angular.module('myModule',
[
'ui.bootstrap',
'ngRoute'
]).controller('ctrl', ['$scope', '$window', function($scope, $window) {
console.log($window.app.requires) // ["ui.bootstrap", "ngRoute"]
console.log(angular.module('myModule').requires) // without global - $window not needed
}]);
JSFiddle Link - working example
Note - If leveraging globals, you can simply call the window as such: window.app.requires - without injecting $window. However, see the AngularJS $window docs to understand why $window is preferred.
Building on #salniro's answer, you don't need globals, or $window.
The dependencies are listed on the .requires property of angular.Module:
angular.module('myModule', [
'ui.bootstrap',
'ngRoute'
])
.controller('ctrl', function() {
var app = angular.module('myModule');
console.log(app.requires); // ["ui.bootstrap", "ngRoute"]
});
http://jsfiddle.net/8vtf6gar/1/
I'm trying to add the bootstrap-ui module to my angular.js project. The documentation states that I simply have to add
angular.module('myModule', ['ui.bootstrap']);
to get this working. But I can't find out how I would add this in any way. I've read the whole chapter of https://docs.angularjs.org/guide/module and read lots of threads about it, but everything I tested didn't work so far.
my app.js:
angular.module('MyApp', ['ngCookies', 'ngResource', 'ngMessages', 'ngRoute', 'mgcrea.ngStrap'])
.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
// followed by my routing
myCtrl
angular.module('MyApp')
.controller('MyCtrl', ['$scope', '$location', '$rootScope', '$routeParams', '$resource', '$alert', 'MyService',
function ($scope, $location, $rootScope, $routeParams, $resource, $alert, MyService) {
what I tried:
adding 'ui.bootstrap' after 'mgcrea.ngStrap' in app.js
adding 'ui.bootstrap' after *'MyService' in myCtrl
many more similar variations
The error messages I get depend on what I did. Since I'm probably completely on the wrong path at the moment I was hoping someone could tell me how I can add a module in angular.js correctly?
edit some error messages I encountered:
When I start my Crtl code with:
angular.module('MyApp', ['ui.bootstrap'])
I get
[ng:areq] Argument 'NavbarCtrl' is not a function, got undefined
(navbarctrl is a completely different ctrl)
when I start my app.js with
angular.module('MyApp', ['ngCookies', 'ngResource', 'ngMessages', 'ngRoute', 'mgcrea.ngStrap', 'ui.bootstrap'])
I get
TypeError: object is not a function
In my AuthService I try to use $alert (this works without bootstrap-ui) like
$alert({
title: 'Success!', //...
**edit 2: ** the problem seems to be that I can only use ngStrp OR ui.bootstrap (both use bootstrap underneath)
Are you ensuring that Angular UI specific JS Files are sent from server to client through bundling or direct reference?
You have to inject dependency of module in your app: something like this angular.module('MyApp', ['ui.bootstrap']);