I see the following angularjs controller syntax structure all the time.
angular.module('7minWorkout').controller('WorkoutController',
['$scope', '$interval', '$location',
function ($scope, $interval, $location)
{
}]);
Why the repetition in the parameter names? Why not just like this
angular.module('7minWorkout').controller('WorkoutController',
['$scope', '$interval', '$location',
function ()
{
}]);
or
angular.module('7minWorkout').controller('WorkoutController',
[
function ($scope, $interval, $location)
{
}]);
The array syntax will help you with minification/uglify of your js code.
angular.module('7minWorkout').controller('WorkoutController',
function ($scope, $interval, $location) {
// code here
});
Will be minified and mangled as:
angular.module('7minWorkout').controller('WorkoutController',
function (a, b, c) {
// code here
});
So Angular won't be able to figure out which dependencies to inject
On the other hand, using the array declaration:
angular.module('7minWorkout').controller('WorkoutController',
['$scope', '$interval', '$location', function ($scope, $interval, $location) {
// code here
}]);
Will be minified as :
angular.module('7minWorkout').controller('WorkoutController',
['$scope', '$interval', '$location', function (a, b, c) {
// code here
}]);
So Angular will know what a, b and c represent.
There's also another way to inject variables if you use your first example code like below:
WorkoutController.$inject = ['$scope', '$interval', '$location'];
or
angular.module('7minWorkout').controller('WorkoutController', /* #ngInject */
function ($scope, $interval, $location) {
// code here
});
which will create the $inject method mentioned above when the code is annotated.
So, there are mainly four kinds of annotation:
Implicit Annotation - the first example code
Inline Array Annotation - the second example code
$inject Property Annotation - the $inject method
$ngInject Comment Annotation - the #ngInject method
ng-annotate
Tools like ng-annotate let you use implicit dependency annotations in your app and automatically add inline array annotations prior to minifying. If you decide to take this approach, you probably want to use ng-strict-di.
For more information, see AngularJS Developer Guide - Using Strict Dependency Injection.
This "repetion" is to make it safe for minification:
AngularJS - Controllers, Dependencies, and Minification
or you can use following syntax, according to popular angular-styleguide https://github.com/johnpapa/angular-styleguide
angular.module('7minWorkout')
.controller('WorkoutController', WorkoutController);
WorkoutController.$inject = ['$scope', '$interval', '$location'];
function WorkoutController($scope, $interval, $location) {
}
You could write the first version since it just omits the parameters of the function which are also accesible via arguments inside the function. So you would avoid the repition but slicing the arguments property is also not really efficient (compared to just type out the parameters).
As the others answers stated the repition is to make it safe for minification.
The first controller syntax makes it possible to minify/uglify the javascript code with the use of tools like ngmin. I'm not quite sure if the 2nd and 3rd options you have provided are viable options to create a controller, but in any case they will not be minified correctly since the tools will not now what the providers are. I would either suggest to use option 1 or option 3 (without the brackets) to create a controller. Note that option 3 will not be minified correctly by automated tools.
Some Useful information about creating controllers:
AngularJS Developer Guide - Controllers
option3 without brackets
angular.module('7minWorkout').controller('WorkoutController', function ($scope, $interval, $location)
{
//Your Code
});
Related
In my angularjs app all my service names start with an uppercase character. I would like to be able the allow service parameters to match the the service name, however the JavaScript "Function Parameter" name rule in Resharper does not allow parameters that start with an uppercase character.
Is it possible to configure or change the JavaScript "Function Parameter" name rule in Resharper to allow service names that start with an uppercase character?Or is there some other way to to avoid this warning?
The BudgetingService parameter in the following code is flagged as a warning by Resharper with the message: "Name 'BudgetingService' does not match rule 'Function Parameter'. Suggested name is 'budgetingService'."
app.controller('BudgetingController',
['$scope', '$rootScope', '$window', 'BudgetingService',
function ($scope, $rootScope, $window, BudgetingService) {
// ...
}]);
Not the answer you are looking for, but there is a reason for that. the only time variables in javascript should be ConstantCamelCase is when they are classes/constructors.
if anything the actual service you create should be budgetingService, not BudgetingService
just lowercase the name it's not work the fight you're trying to put up
app.controller('BudgetingController',
['$scope', '$rootScope', '$window', 'BudgetingService',
function ($scope, $rootScope, $window, budgetingService) {
budgetingService.whatever()
// ...
}
]);
if you REALLY want to have it uppercase, redeclare it after injecting
app.controller('BudgetingController',
['$scope', '$rootScope', '$window', 'BudgetingService',
function ($scope, $rootScope, $window, budgetingService) {
var BudgetingService = budgetingService;
// ...
}
]);
Resharper provides a documentation to change default namings
Here is documentation https://www.jetbrains.com/help/resharper/2016.3/Coding_Assistance__Naming_Style.html
I know that it isn't good practice to have multiple ng-apps in a project but my project is divided into segments that aren't generally related to each other, plus I am left with more or less no other option.
My problem is the persistence of ng-cookie amidst two separate Javascript files. Let's say I have dashboard1.html that is linked to controller1.js and dashboard2.html linked to controller2.js.
Now, I want to access the cookie value of controller 1 in controller 2. When I try to do this the result says undefined and that means I cannot access the cookie value set by another Javascript file.
Please advise me how to solve this issue.
NOTE : Javascript files have respective ng-app defined and controller for each application.
This is Controller and ng-app part of one module.
var app = angular.module('mainpageapp', ['ngRoute','ngCookies']);
app.controller('ctrlmainpage', ['$scope', '$timeout','$http', '$route', '$routeParams', '$location', '$rootScope', '$cookies', function ($scope, $timeout, $http, $route, $routeParams, $location, $rootScope, $cookies) {
console.log("Csadad");
$cookies.myFavorite = 'TestCookie';
var favoriteCookie = $cookies.myFavorite;
console.log("Cookie" + favoriteCookie);
Now in this ng-app's controller I am setting a cookie, it works properly and I do get expected response on console. This is in file controller1.js
Now I am trying to access the same cookie in controller2.js that is all together bound by different ng-app.
var app = angular.module('myApp', ['ngRoute', 'smart-table', 'ngCookies']);
var id = 'hasdh';
app.controller('dashmerctrl', ['$scope', '$timeout','$http', '$route', '$routeParams', '$location', '$rootScope', '$cookies', function ($scope, $timeout, $http, $route, $routeParams, $location, $rootScope, $cookies)
{
var favoriteCookie1 = $cookies.myFavorite;
console.log("Cookie1" + favoriteCookie1);
Her I get undefined as output.
I want to access that same cookie in this file.
if you wish to share data across tabs or domains you can give zendesk's "cross-storage" a try, just implemented it with AngularJS and it works like a charm.
it utilizes window.postMessage() technique to achieve this behavior.
link: zendesk/cross-storage
I am working on a trivial task (that I got working) which adds an an .active class to dom elements in a tab nav. Simple. Got it working by following https://stackoverflow.com/a/12306136/2068709.
Reading over the answer provided and comparing their controller to example controllers on angular's website I came across something interesting that I don't quite understand.
On the AngularJS website, $scope and $location (and other services) are injected into the controller along with an anonymous function which defines the controller. But on the answer, the services are not injected, rather they are passed via the anonymous function. Why does this work? Shouldn't the service always be injected?
In terms of an example: Why does this
angular.module('controllers', [])
.controller('NavigationController', ['$scope', '$location', function($scope, $location) {
$scope.isActive = function(route) {
return route === $location.path();
};
}])
and this
angular.module('controllers', [])
.controller('NavigationController', function($scope, $location) {
$scope.isActive = function(route) {
return route === $location.path();
};
})
both work?
This may be trivial but its throwing my brain for a loop that I can't figure out.
The two examples are equivalent - they just make use of different syntax. The first example uses what they call "inline array annotation" (see here). The purpose of this alternate syntax is just to allow a convenient way to make the injected variable names different than the name of the dependency.
So for example, if you wanted the variable names to be "s" and "l", then you could write:
angular.module('controllers', [])
.controller('NavigationController', ['$scope', '$location', function(s, l) {
s.isActive = function(route) {
return route === l.path();
};
}]);
Actually they are injected in both cases, the difference between those two cases is in the first scenario you define and name the dependency this could be useful if you minify your js code and that way you are declaring explicitly the dependency for examply it could be:
angular.module('controllers', [])
.controller('NavigationController', ['$scope', '$location', function($s, $l) {
$s.isActive = function(route) {
return route === $l.path();
};
}])
that way angular will know which dependency to inject on which parameter without looking at the naming for each parameter.
the other case you need to be explicit and declare which dependency you'll inject by setting up the name.
I hope that helps.
This is how angular handles code minification. by keeping strings intact it can keep mapping vars when they are renamed.
if you take a look at the code of the controller https://github.com/angular/angular.js/blob/master/src/ng/controller.js#L48
you'll see that the constructor can accept both function and array.
app.controller('myController', ['$scope', '$http', '$filter', function($scope, $http, $filter) {
The above is an example of my code where I am trying to use $http.get and also $filter inside my controller.
The only problem is when I use it like so, the console log throws an error that says $filter is not a function.
app.controller('myController', ['$scope', '$http', '$filter', function($scope, $filter, $http) {
When I swap them round it throws an error that $http is undefined
When you are using
app.controller('myController', ['$scope', '$http', '$filter', function($scope, $filter, $http) {
variable $filter is actually a instance of $http, and $http is instance of $filter. Actually it doesn't matter what is written in function(...) params.
What is important here, is the order of injectibles you are using, for example
app.controller('myController', ['$scope', '$http', '$filter', function(a, b, c) {
will map to instances:
a -> scope
b -> $http
c -> $filter
From angular docs:
Since Angular infers the controller's dependencies from the names of arguments to the controller's constructor function, if you were to minify the JavaScript code for PhoneListCtrl controller, all of its function arguments would be minified as well, and the dependency injector would not be able to identify services correctly.
So by using array notation for yout controller, you are making sure that code will work after code is minified.
add filter after http and angular version also defends how you are
going to use filter.
plateFormController.$inject = ['$scope', '$http',
'$filter','$timeout', '$q', '$mdSidenav', '$log'];
function plateFormController($scope, $http,$filter, $timeout, $q) {
jsonByName=$filter('filter')($scope.json, { name: 'a' });
}
In my case, expected data List object is null, by ensuring that expected List Object not null. I am able to avoid this error.
I am trying to run my AngularJS front-end on server. I am using Yeoman to build the app. I upload the very basic hello world app and I get plain HTML text withou JavaScript loaded. Console in Chrome says this:
Error: Unknown provider: aProvider <- a
at Error (<anonymous>)
at http://../scripts/vendor/d10639ae.angular.js:2627:15
at Object.getService [as get] (http://../scripts/vendor/d10639ae.angular.js:2755:39)
at http://../scripts/vendor/d10639ae.angular.js:2632:45
at getService (http://../scripts/vendor/d10639ae.angular.js:2755:39)
at invoke (http://../scripts/vendor/d10639ae.angular.js:2773:13)
at Object.instantiate (http://../scripts/vendor/d10639ae.angular.js:2805:23)
at http://../scripts/vendor/d10639ae.angular.js:4620:24
at update (http://../scripts/vendor/d10639ae.angular.js:13692:26)
at http://../scripts/vendor/d10639ae.angular.js:8002:24 d10639ae.angular.js:5526
Anybody experiencing the same and knows the way out?
EDIT:
'use strict';
yoAngApp.controller('MainCtrl',['$scope', '$window', function($scope, $window) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Testacular'
];
$scope.records = [{ title : 'one' }, { title : 'two' }, { title : 'three' }, { title : 'four' }];
$scope.greet = function() {
($window.mockWindow || $window).alert('Hello ' + $scope.name);
}
}]
);
I'm pretty sure that you have used code minifier for production server, am I right?
Anyways, the folks from Angular Js made pretty clear that using minifier can mess up Dependency Injection if it's not done properly. Why this happens? Have a look:
Dependency Injection vs. Code Minifier
function MyController($scope, $log) { ... }
In the snippet above you are making use of implicit DI. Angular sees variable $scope and tries to match it with any managed dependency. In this example it will match it to the $scope object.
This, however, will not work after code minifying, as the result will look somehow like this:
function a(b, c) { ... }
Since variable and function names were minified, Angular cannot know what exactly an "a" is.
Solution
Use explicit Dependency Injection configuration.
var MyController = function($scope, $log) { ... }
MyController.$inject = ['$scope', '$log'];
In this snippet you are defining which dependencies should be resolved by attaching array of their names to special property of controller (or service) called $inject. Now Angular will know that it should resolve $scope and pass it as first parameter to MyController. Then it will resolve $log and pass it as second parameter.
It's all possible because minifiers won't modify the contents of string variables.
As #ĆukaszBachman suggested, you may use $inject annotation or you may use Inline Annotation if you want to:
Keep your dependency annotations close to your function definitions (for better readability).
Stay away from polluting global namespace.
app.controller('UsersController',
[
'$scope', 'UserService', '$location', '$routeParams',
function($scope, User, $location, $routeParams) {
$scope.user = User.get({id: $routeParams.id});
...
}
]
);