angularjs constant how to use Unknown provider - javascript

I'm wondering what's wrong with this snippet
var app = angular.module('myApp', []);
app.constant('_START_REQUEST_', '_START_REQUEST_');
app.constant('_END_REQUEST_', '_END_REQUEST_');
app.config(function($httpProvider, _START_REQUEST_, _END_REQUEST_) {
});
it give me
Unknown provider: START_REQUEST from myApp
Bye

It turns out that it is the way you have named your constants that is causing the problem.
If you change _START_REQUEST_ & _END_REQUEST_ to START_REQUEST & END_REQUEST it works.
It must be something to do with the _ at the start of the name.
This may be a bug or there may be a reason for it, but as it stands I don't know why angular doesn't accept the names like that.
Demo with no errors in console http://jsbin.com/UZaquNu/1/edit

Related

Allow skype calls from Angular App (using meanjs)

I can not get rid of a small issue affecting my app functionality to enable to call a phone number using skype, what I have so far is this:
HTML:
<a ng-href="skype:{{user.phone}}?call" class="btn btn-sm btn-success" type="button">{{user.phone}}</a>
ANGULAR
(function() {
angular.module('core').config(coreConfig);
coreConfig.$inject = ['$compileProvider'];
function coreConfig($compileProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|file|skype):/);
}
})();
The result is always the same, when I hover the element to start a call the browser show this: unsafe:skype:012345678?call and do not allow me to call the number...
I added the config part browsing other questions related to similar issues but it doesn't solve my issue.
EDIT:
I'm using meanjs.org
EDIT 2:
Please do not copy/paste my question code as your answer... I know that it work on a normal Angular application. The problem is that I can not let it work using meanjs.org app. Thanks.
EDIT 3:
I just found that: if I use the skype link in the main root / or in a child root like: /list it work fine without adding the unsafe prefix. In a dynamic root like: /list/1234 it doesn't work anymore. I don't know if it could help.
The "bug" was caused by an old version of ngFileUpload that overwrite my configuration as reported here.
Upgrading the version of ngFileUpload solved my issue.
Thanks for your help.
You need to explicitly add URL protocols to Angular's whitelist using a regular expression. Only http, https, ftp and mailto are enabled by default. Angular will prefix a non-whitelisted URL with unsafe: when using a protocol such as chrome-extension:.
A good place to whitelist the chrome-extension: protocol would be in your module's config block:
var app = angular.module( 'myApp', [] )
.config( [
'$compileProvider',
function( $compileProvider )
{
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension):/);
// Angular before v1.2 uses $compileProvider.urlSanitizationWhitelist(...)
}
]);
The same procedure also applies when you need to use protocols such as file: and tel:.
Please see the AngularJS $compileProvider API documentation for more info.
I've made it work in following plunker
http://plnkr.co/edit/rIPFz9WhFjlRJ1ogCArP?p=preview
angular.module('plunker', [])
.config(function($compileProvider){
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|skype|mailto|tel|file):/)
})
.controller('MainCtrl', function($scope) {
$scope.href = 'skype:123456?call';
});

My Angular app only works with a certain syntax

I'm following a thinkster tutorial on angular and rails. The tutorials says to make the app like this...
angular.module('flapperNews', [])
with the controllers and factories like this...
.config([...
.controller([...
.factory([...
and so on. However it only works when I do this...
var flapperNews = angular.module('flapperNews', [])
with the controllers and factories like this...
flapperNews.config([...
flapperNews.controller([...
flapperNews.factory([...
Is there a short answer for this? Is the tut wrong or am I doing something wrong.
Here is the tut link
https://thinkster.io/angular-rails#introduction
I haven't started the rails part yet, just wanted to know why it breaks.
Here are the two codepens...
This one works as described above.
http://codepen.io/MrNagoo/pen/regKgM
This one fails and gives errors, although it's how i'm being directed to write the code...
http://codepen.io/MrNagoo/pen/regKEM
I would suggest looking at John Papa's style guide: https://github.com/johnpapa/angular-styleguide/tree/master/a1
You create your module as you said:
angular.module('flapperNews', [])
And you add a controller/factory/config/whatever like:
angular
.module('flapperNews')
.config(config)
function config() { ... }
Your problem is that you are using ; before doing the next .config this terminate the statement. You need to chain the components.
angular.module("app",[])
.config()
.controller()
.service();
here is the codepen with the working code
But you should definettly follow John Papa's style guide

Angular, trouble getting directive to work

I seem to be having trouble getting my directive to work, I think I may be registering it incorrectly, but I can't seem to figuire out how. Possibly the naming convention?
Here's what I have -
My Directive -
'use strict';
angular.module('demoApp')
.directive('packeryAngular', ['$rootScope', '$timeout',
function($rootScope, $timeout) {
return {
restrict: 'A',
scope: true,
link: function(scope, element, attrs) {
};
}
]);
On my div, I just call it like so
<div packeryAngular>
However, when I call it just like this, nothing seems to be happening. My first assumption was that I needed to register on my app like so
angular.module('demoApp', [ 'packeryAngular ']
However, when I do that I get the error in the console of :
Error: [$injector:modulerr] Failed to instantiate module packeryAngular due to:
Error: [$injector:nomod] Module 'packeryAngular' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
So, I'm pretty new to this but I'm not entirely sure what I'm doing wrong here, I've tried to copy other working examples and can't seem to get it working. Would appreciate any help, and thank you very much for reading!
You dont need to inject the directive , you just need to use it in html .Second Word of Directive with capital first letter becomes small proceeding with a hyphen,So on all next Capital first letters will become small and will be preceded with hyphen like yourCustomDirective becomes your-custom-directive
<div packery-angular>
get rid of injecting it in module
angular.module('demoApp', []);
You must put the following attribute on your node:
<div packery-angular>
When registering your directives, your names must use the lower camel case form. But HTML does not deal well with upper case letters in attribute names, so AngularJS expects upper case letters to be replaced by a dash followed by their corresponding lower case letter.
So your directive name in javascript code is yourDirectiveName, but in the HTML code, it must be referred as your-directive-name.

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