Should angular.module be set variable on AngularJS - javascript

I’ve read two AngularJS sample on Github. I’m confused to how to modularize controller. The first on is set variable(foodMeApp) and re-use it. Controllers need less arguments. It’s easier to read.
But, second one doesn’t use variable(foodMeApp) and has more arguments. I think this way is frequently used on AngularJS samples.
Is this any merit to use the second way?
1.https://github.com/IgorMinar/foodme
var foodMeApp = angular.module('foodMeApp', ['ngResource']);
foodMeApp.constant('CONFIG_A', {
baseUrl: '/databases/',
});
foodMeApp.controller('HogeController', function HogeController($scope, CONFIG_A) {
console.log(“less arguments");
});
2.https://github.com/angular-app/angular-app
angular.module('foodMeApp', ['ngResource']);
angular.module('foodMeApp').constant('CONFIG_B', {
baseUrl: '/databases/',
});
angular.module('foodMeApp').controller('HogeController', ['$scope', 'CONFIG_B', function($scope, CONFIG_B) {
console.log("more arguments");
}]);

since angular.module('...') ,constant,provide,controller,factory ... return the same mdoule you can chain module method calls if you want to or not... it's just javascript.
you can write
angular.module('foo',[])
.controller('bar',function(){})
.service('baz',functinon(){})
.constant('buzz',something)
.value('bizz',somethingelse);
it makes no different.

This example is using an array for your dependencies which are going to be injected into your controller. The array method is typically used when the code is going to minified at some time and allows angularjs to know exactly which items will be injected. If this array were not there, angular would only see 'a', 'b' as the items injected into the function and would not be able to figure out what those things were. Items in the array are strings and will not be changed when the minification happens.
angular.module('foodMeApp').controller('HogeController', ['$scope', 'CONFIG_B',
function($scope, CONFIG_B) {
console.log("more arguments");
}]);
Hope this helps explain the differences which you have seen.

There is no such 'merit' of going for 2nd option. 1st approach is more popular as it avoids repeating angular.module('foodMeApp') so many times.
If you give it a name "foodMeApp" you can directly use foodMeApp as you would have used in 2nd approach. Less repetition, simpler life.

Related

What is the point of naming an anonymous function in a directive?

I came across some standards that basically said all the functions in directives and controllers in angular should be named. I am not talking about naming functions inside the controller or directive, I am talking about in the line where the directive is being called.
Example of how I would usually write this:
angular.module('myModule',[])
.directive('myDirectiveName', function (){
return{
controller: function($scope){
//some code
}
}
});
How this guide is asking it to be written:
angular.module('myModule',[])
.directive('myDirectiveName', function directiveInit(){
return{
controller: function controllerInit($scope){
//some code
}
}
});
Obviously, the difference here being directiveInit and controllerInit.
What is the point of this? Is it for better debugging errors? I know it is not needed. Does this make something easier? Is it an angular specific practice?
EDIT: Is there a better title I can use for this? I don't feel like the title is accurately reflecting what I am asking.
Well naming functions even if they don't seem necessary to be named, is a practice for maintainability resons.
One of them is to make the function trackable, for debug and profiling tools. When you are profiling your code to track performance issues, you better know the name of the function otherwise you will only see anonymous function which wouldn't help much on your profiling activity.
Other reason, is for code readability improvements, especially for teams. For exemple, in angularjs (v1.x) directives are very often declared like so:
(function(){
angular
.module('myModule')
.directive('myDirectiveName', myDirectiveName);
function myDirectiveName(){
function controllerInit($scope){
//some code
}
return{
controller: controllerInit
}
}
})();
Which in my opinion is way more easy to read than anonymous directive constructors. Also, it make more easy to handle such thing as encapsulation and stuff.

Replace assignment with deferred assignment

In my angular.js page I extend $scope with all attributes I need.
Before, I simply extended $scope with
angular.extend($scope,{
myAttr : aService.getValues()
});
However, turns out I have to add a promise (angular file access) to aService.getValues. Hence, I cant keep the above syntax but have to replace it with
angular.extend($scope,{
myAttr : null
});
aService.getValues().then(function(values){$scope.myAttr = values;})
That's annoying because I have to replace quite a bit of code and am afraid to add bugs. Any alternatives?
The only thing I can suggest is a slightly prettier re-doing of your own solution:
aService.getValues().then(function(values) {
angular.extend($scope, {
myAttr: values
})
});
Is it critical that $scope is extended synchronously? If it is, I don't see any way of feeding asynchronous data into it any other way.
EDIT
If you're reworking your logic, consider using $stateProvider with a resolve property: https://github.com/angular-ui/ui-router/wiki (Scroll down to the section that talks about resolve). Long story short, everything in the resolve must run before the state controller is initialized. This way you can do all your async operations in the resolve, and only let it load after you have everything you need.

Why does angular define "priority" property for directives that are defined on the same DOM element?

I've found that angular doesn't take advantage of order the directives are defined in, instead it uses static priority field. It does not suite well for all cases.
Example:
<div ng-if="items.length < 50" ng-repeat="item in items"></div>
<div ng-repeat="item in items" ng-if="items.length > 50"></div>
These two lines of code can have different meaning.
Case 1) check if amount of items less than 50, ng-repeat 10000 items
Case 2) ng-repeat 10000 items, then on each element check if amount of items is less than 50
If ng-if had higher priority the first line of code would allow obviously very important optimization...
Obviously there is not much reason for using static "priority" field compared to prioritizing directives with order they are defined in, so my question is:
What steps should be taken to approve this idea and have it implemented?
(I was never looking into angularjs source code, some external help is required to point-out the places that need to be changed in order for providing the subject approach, I would be thankful for any external help in this direction)
Thank you in advance!
Edit
Here's a jsFiddle showing that ng-if is getting executed 20000 times for an array of 10000 items, each ng-if creates a scope which doubles the problem...
http://jsfiddle.net/u840t0dh/17/
I can't find a reason on why angular doesn't take advantage of order the directives are defined in, rather than using static priority field, it does not suite well for all cases.
The idea of angular directives is to extend browser built-in markup languages (tags, attributes, ...). I believe there is no such feature in standard browser markup. I want to stress that directives in angular is declarative programming.
For the problem you pointed out, it looks to me like imperative programming. It's like you're coding your logic in the page with an if and a loop. But in your case, it does not make much sense to use them on the same element => it's very similar to writing if and for loop on the same line in any imperative programming languages (c++, c#, java,...). It makes more sense to write it like this if you follow imperative programming mindset:
<div ng-if="items.length > 50">
<div ng-repeat="item in items"></div>
</div>
I agree that sometimes in order to write UI rendering code, we have to write a bit like imperative programming but it could be kept to the bare minimum. Even in those case, if you follow the mindset of imperative programming (like the one I pointed out), there should not be a problem.
Therefore, the problem you pointed could be a problem but actually not a big problem compared to the advantages that we gain from declarative markups.
Declarative programming and imperative programming has their own pros and cons:
http://en.wikipedia.org/wiki/Declarative_programming
https://softwareengineering.stackexchange.com/questions/32781/declarative-programming-vs-imperative-programming
For the case of directives to extend "markup", it makes more sense with declarative programming which is the way angular directives were designed (markup is really declarative)
The point of declarative programming is about telling "what" you want, not "how" to do it. That comes with the benefit: it's simpler and easier to understand.
From MSDN
In fact, the ease of understanding code—even in an unfamiliar
context—is one of the principal benefits of a declarative style.
The most notable benefit of declarative programming is that programs
specify “what” we want to get as the result rather than “how”. As a
result, it is more important to understand the domain that we’re
working with than every detail of the language.
With your suggestion, it's more about "how" you want to get a task done. The downside of your suggestion is that when we use directives, we need to understand how they work "internally".
For example: when you use many directives on the same element, the person who uses the directives need to understand what is the order to put the directives (that's should be the concern of the person who implements the directives). That's something declarative programming tries to avoid because it's complex for users of the directives
To answer your question, there are several possible use cases for Priority. I am not saying they are common, but they are possible and potentially very powerful…
Here are two examples:
Use case A) Wrapping any directive.
By using priority you can get custom code running before or after a given directive.
Suppose you have an existing angular application with thousands of ng-click directives, and want to run something before every single ng-click. You can do something like this:
angular.module('app', [])
.directive('ngClick', function($rootScope) {
return {
restrict: 'A',
priority: 100,
link: function(scope, element, attr) {
element.bind('click', function(ev) {
alert("custom click running");
})
}
}
})
.controller('MyCtrl', function($scope) {
$scope.alert = function() {
alert('built-in click running!')
}
})
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#1.0.7" data-semver="1.0.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
</head>
<body ng-controller="MyCtrl">
<a ng-click="alert()">Click me</a>
</body>
</html>
Here your custom click will run before angular build in click.
Use case B) terminating execution
By using priority and terminal: true, you can prevent other directives from executing. For example on all delete actions you can use a custom directive to ask for confirmation. in this case using DOM defined order will be dangerous because you are deleting records.
var app = angular.module('terminal', []);
app.controller('MainCtrl', function($scope) {
$scope.deleteIt = function() {
window.alert('Delete called!');
}
});
app.directive('confirmationNeeded', function() {
return {
priority: 10,
terminal: true,
link: function(scope, element, attr) {
var msg = attr.confirmationNeeded || "Are you sure?";
var clickAction = attr.ngClick;
element.bind('click', function() {
if (window.confirm(msg)) {
scope.$eval(clickAction)
}
});
}
};
});
<!doctype html>
<html ng-app="terminal">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
</head>
<body ng-controller="MainCtrl">
Delete with custom message
</body>
</html>

How to fix injector error after Angular minification build?

Before speaking, I read about it made ​​recommendations but still causing error. Look the short code:
function IndexController($scope, $route, $routeParams, $location){
$scope.sfv = project.version.name;
}
angular.module("TkwebMobile", ['ngRoute', 'ngCookies'])
.controller('IndexController', ['$scope', '$route', '$routeParams', '$location', IndexController]);
Only this and the error persists. I'm using grunt to "uglify", and I'm also using the "concat" to unite the codes in a "lib". Even I using "injection" recommended in the Angular documentation.
Uncaught Error: [$injector:modulerr] Failed to instantiate module TkwebMobile due to:
Error: [$injector:unpr] Unknown provider: a
Is it problem of grunt concat? (grunt-contrib-concat)
This is due to your minification, specifically options to minify and mangle your variable names.
Angular determines what value to inject into your functions from the name of the parameters. For example...
angular.factory('MyFactory', function($location) {...});
...will cause angular to look for whatever dependency is named '$location' and then call your function with the $location value passed as it's parameter.
When you minify your javascript, with an option called mangle turned on, then the variable names get mangled. The previous function will turn into this...
angular.factory('MyFactory', function(a) {...});
Angular no longer has the correct parameter name in your source code, as $location is now a. This saves on size of your javascript but totally destroys Angular's implicit dependency resolution. You can solve this in one of two ways.
The first is a feature that angular provides for you.
angular.factory('MyFactory', ['$location', function(a) {...}]);
You provide the names of the parameters in an array, with the last element of the array being the function to inject the parameters into. This way, it doesn't matter what you call your parameters in the code, and the minifier will never change a string literal so Angular always knows what you're wanting.
The other way if you don't want to lose the convenience of not having to use the array notation is to turn off the mangle setting on your minifier. This obviously means you don't minify to the same degree, but ask yourself if it's really worth those extra bytes.
A halfway house is to use something like ngMin, to allow annotation of the array notation into your code and then continue with the minification. This is the best of both world's imo, but increases the complexity of deploying your clientside js.
EDIT
The correct settings to turn off the mangle behaviour in grunt would be this...
uglify: {
options: {
report: 'min',
mangle: false
}
}
But the ngAnnotate package can avoid this. See here for more info. (ngAnnotate is the package that has taken over ngMin)
I've had a similar problem. It turned out that I was not properly identifying and formatting the dependencies for controllers and services, etc. I believe I discovered this by looking at the minification output. (It was rough, let me tell you.)
Basically I had to look through all my files and verify that the dependency list matched what I was using in my controllers and services. It's strange because it worked without the changes.
Here is an example of what I had to do:
Original:
angular.module('FootCtrl', []).controller('FooterController', function($scope) {
$scope.footer = 'Copyright \u00A9 ' + new Date().getFullYear() + name;
});
Fixed
angular.module('FootCtrl', []).controller('FooterController', ["$scope", function($scope) {
$scope.footer = 'Copyright \u00A9 ' + new Date().getFullYear() + name;
}]);
Maybe take note of where I use single quotes vs. double quotes as well.
Hopefully this helps a bit. I'm not sure if you have more code than what is shown- if not, I'm not too sure.
I had this problem and it took me a lot of time to figure out what the issue was because I tried disabling mangling of variable names, using $inject array instead of just passing the services and provider names to function definitions while relying on angular implicit dependency injection but still the problem persisted. It turned out that in one of my controller which uses IIFE, was missing semicolon at the end. Look at the code below.
Before:
(function(){
})()
The above code works okay before minification due to automatic semicolon insertion but it breaks after minification because the absence of semicolon screw things up. So after correction it looked like below.
Correct:
(function(){
})();
This fixed my problem. I hope this might help some one
Note: I use grunt useminPrepare, usemin, copy, uglify and ngAnnotate.

AngularJS Controllers: The Right Way

So, I've been talking with co-workers about the "right way" to create an AngularJS controller. I know there are several ways of creating one, but I'm interested in getting my team writing them the same way AND the "right" way. By "right way" I'm talking about easy to read, testable, and performant. I'm sure there are competing theories on the best way to create a controller, but I'm most interested in test-ability at the end of the day since that is what AngularJS is built to do well.
Without further ado, here's the contenders:
Let's assume that our app is declared as so: var app = angular.module('app',[]);
1.
app.controller('myCtrl', function(){
...
});
2.
function myCtrl = {
...
}
app.controller('Ctrl', myCtrl);
3.
(function(app) {
app.controller('myCtrl', function() {
...
}
})(app);
Please let me know if I've missed one.
This does not take into consideration the changes needed for minification so please do not add that to this conversation.
Thanks! (I hope this doesn't start a flame war ><)
My team exclusively uses 1. I've considered 3 as well, and we just have a standing rule (and jshint constraint) about global level code. I would never use 2.
I always do it this way:
angular.module('myModule').controller('MyController', ['$scope', function($scope) {
<stuff>
}]);
Yes, it's a little more verbose, but it creates nothing in global scope, it is very clear what module the controller belongs to, and if I need to separate my controller into another file I just copy and past it without worrying about where 'app' is defined or about whether I missed a '.' in a chained declaration.
And I know I was supposed to ignore it, but of course this version is minification safe.
In general I believe you should find a clear standard and stick to it. That way if something doesn't look "right" you can tell right away.
The Angular team recently posted a best practices guide so that might be a good place to start: http://blog.angularjs.org/2014/02/an-angularjs-style-guide-and-best.html. Also this presentation discusses some best practices on creating controllers: https://docs.google.com/presentation/d/1OgABsN24ZWN6Ugng-O8SjF7t0e3liQ9UN7hKdrCr0K8/present?pli=1&ueb=true&slide=id.p
If you were using number 2 you wouldn't really need app.controller('Ctrl', myCtrl);. You can reference a controller from ng-controller even if it isn't defined with module.controller(...)
You might want to also consider making your controller as much like "classes" as javascript will allow and using the 'controller as' syntax.
var myApp = angular.module("myApp", []);
myApp.MyCtrl = function($log) {
this.$log = $log;
}
myApp.MyCtrl.prototype.sayHello = function() {
this.$log('hello');
}
There are cases where it may be useful to have your controllers globally accessible. Like if you want to create an instance of your controller with $injector.instantiate() you need to have access to its constructor (although you could use the $controller service to accomplish the same goal using a string).
var myCtrl = $injector.instantiate(myApp.MyCtrl); //Works
var myCtrl2 = $injector.instantiate('MyCtrl'); //Doesn't Work
But if you don't have a specific use case for making your controllers global you should probably encapsulate them with module.controller(...);.
This answer also advocates using module.controller() https://stackoverflow.com/a/13363482/373655

Categories

Resources