I was just going through the code of a online reppositoty using angular.js and came across the following example:
<!DOCTYPE html>
<html ng-app="demoapp">
<head>
<script src="js/ol.js"></script>
<script src="js/angular.min.js"></script>
<script src="js/angular-sanitize.min.js"></script>
<script src="js/angular-openlayers-directive.js"></script>
<link rel="stylesheet" href="css/ol.css" />
<link rel="stylesheet" href="css/angular-openlayers-directive.css" />
<script>
var app = angular.module('demoapp', ['openlayers-directive']);
</script>
</head>
<body>
<openlayers lat="39.92" lon="116.38" zoom="10" height="400" custom-layers="true">
<ol-marker lat="39.92" lon="116.38" message="Here is Beijing. Dreamful place.">
</ol-marker>
</openlayers>
<h1>Adding a layer with markers with no javascript example</h1>
</body>
</html>
Now there is the below part:
var app = angular.module('demoapp', ['openlayers-directive']);
I am not quite sure about, the above line, I read about dependency injection HERE. But i am not quite sure what is the purpose of the above line ? what is it really doing ?
I have gone though a few online examples that have code like the below:
// Define a new module for our app. The array holds the names of dependencies if any.
var app = angular.module("instantSearch", []);
(See the comment) , Ok but i still don't get what ['openlayers-directive'] , is doing ?
It declares a module named 'demoapp' that is dependant on a module named 'openlayers-directive'. This, basically, means that all the angular components (directives, services, filters, controllers, constants, etc.) defined in the module 'openlayers-directive' will be usable in your angular application.
Read the documentation.
openlayers-directive is an angular module. When you are creating your demo app module, you are including a reference to the openlayers module.
So if you wanted to use other modules in your demo app module you would also include them here, where you are declaring your module for the first time.
For example:
var app = angular.module('demoapp', ['openlayers-directive', 'anotherModule', 'yetAnotherModule']);
In your code you can then pass in any services from these modules by simply including them as parameters.
So if you have a demoController you could pass in a service from one of the included modules and use it.
For example
angular.module('demoApp').controller('demoContoller', function($scope, anotherModuleService)
{
$scope.someFunctionFiredFromController = function()
{
//I have access to this service because the module it
//belongs to was referenced by the demoApp module, and the
//service was injected into the controller
anotherModuleService.doSomethingRelevant();
}
});
I am newbie to Angularjs. I am trying to create simple directive with the following code:
View:
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<user-info></user-info>
</div>
</body>
</html>
Controller:
myapp = angular.module("myapp", []);
myapp.directive('userInfo', function() {
var directive = {};
directive.restrict = 'E'; /* restrict this directive to elements */
directive.template = "My first directive: ";
return directive;
});
I am following this Tutorial to learn directive
http://tutorials.jenkov.com/angularjs/custom-directives.html
I am getting error:
http://errors.angularjs.org/1.3.14/$injector/modulerr?p0=myApp&p1=Error%3A%20%5B%24injector%3Anomod%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.3.14%2F%24injector%2Fnomod%3Fp0%3DmyApp%0A%20%20%20%20at%20Error%20(native)%0A%20%20%20%20at%20http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A6%3A417%0A%20%20%20%20at%20http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A21%3A412%0A%20%20%20%20at%20a%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A21%3A53)%0A%20%20%20%20at%20w.bootstrap%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A21%3A296)%0A%20%20%20%20at%20http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A35%3A46%0A%20%20%20%20at%20s%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A7%3A302)%0A%20%20%20%20at%20g%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A34%3A399)%0A%20%20%20%20at%20ab%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A38%3A135)%0A%20%20%20%20at%20d%20(http%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.14%2Fangular.min.js%3A17%3A381
Here is my codepen link
http://codepen.io/anon/pen/NGNKxz
You have error in the name of your app :
myapp = angular.module("myApp", []); // not 'myapp'
Add Your Directive
You need to add the directive to your html like so
<script src="path/to/your/directive.js"></script>
or if your working from one module you will link to the main module. But please restructure your app like this it will keep code up to standard and clean.
I have a git hub repo where I am building an app in this structure here. Best of luck.
Note
You are using angular min. Min is great for production because its small and faster to load but your in development at the moment so use the full version so you can capture errors better with the browser console.
Looks like you did not declare the controller myCtrl. Your directive looks fine.
myapp.controller('myCtrl', function() {
});
Is it the current version of your html file ?
Because you might need to link your controller, between head tags, insert :
<script src="the js file which contains your controller"></script>
or
<script>Your controller</script>
I am writing a sample application using angularjs. i got an error mentioned below on chrome browser.
Error is
Error: [ng:areq] http://errors.angularjs.org/1.3.0-beta.17/ng/areq?p0=ContactController&p1=not%20a%20function%2C%20got%20undefined
Which renders as
Argument 'ContactController' is not a function, got undefined
Code
<!DOCTYPE html>
<html ng-app>
<head>
<script src="../angular.min.js"></script>
<script type="text/javascript">
function ContactController($scope) {
$scope.contacts = ["abcd#gmail.com", "abcd#yahoo.co.in"];
$scope.add = function() {
$scope.contacts.push($scope.newcontact);
$scope.newcontact = "";
};
}
</script>
</head>
<body>
<h1> modules sample </h1>
<div ng-controller="ContactController">
Email:<input type="text" ng-model="newcontact">
<button ng-click="add()">Add</button>
<h2> Contacts </h2>
<ul>
<li ng-repeat="contact in contacts"> {{contact}} </li>
</ul>
</div>
</body>
</html>
With Angular 1.3+ you can no longer use global controller declaration on the global scope (Without explicit registration). You would need to register the controller using module.controller syntax.
Example:-
angular.module('app', [])
.controller('ContactController', ['$scope', function ContactController($scope) {
$scope.contacts = ["abcd#gmail.com", "abcd#yahoo.co.in"];
$scope.add = function() {
$scope.contacts.push($scope.newcontact);
$scope.newcontact = "";
};
}]);
or
function ContactController($scope) {
$scope.contacts = ["abcd#gmail.com", "abcd#yahoo.co.in"];
$scope.add = function() {
$scope.contacts.push($scope.newcontact);
$scope.newcontact = "";
};
}
ContactController.$inject = ['$scope'];
angular.module('app', []).controller('ContactController', ContactController);
It is a breaking change but it can be turned off to use globals by using allowGlobals.
Example:-
angular.module('app')
.config(['$controllerProvider', function($controllerProvider) {
$controllerProvider.allowGlobals();
}]);
Here is the comment from Angular source:-
check if a controller with given name is registered via $controllerProvider
check if evaluating the string on the current scope returns a constructor
if $controllerProvider#allowGlobals, check window[constructor] on the global window object (not recommended)
.....
expression = controllers.hasOwnProperty(constructor)
? controllers[constructor]
: getter(locals.$scope, constructor, true) ||
(globals ? getter($window, constructor, true) : undefined);
Some additional checks:-
Do Make sure to put the appname in ng-app directive on your angular root element (eg:- html) as well. Example:- ng-app="myApp"
If everything is fine and you are still getting the issue do remember to make sure you have the right file included in the scripts.
You have not defined the same module twice in different places which results in any entities defined previously on the same module to be cleared out, Example angular.module('app',[]).controller(.. and again in another place angular.module('app',[]).service(.. (with both the scripts included of course) can cause the previously registered controller on the module app to be cleared out with the second recreation of module.
I got this problem because I had wrapped a controller-definition file in a closure:
(function() {
...stuff...
});
But I had forgotten to actually invoke that closure to execute that definition code and actually tell Javascript my controller existed. I.e., the above needs to be:
(function() {
...stuff...
})();
Note the () at the end.
I am a beginner with Angular and I did the basic mistake of not including the app name in the angular root element. So, changing the code from
<html data-ng-app>
to
<html data-ng-app="myApp">
worked for me. #PSL, has covered this already in his answer above.
I had this error because I didn't understand the difference between angular.module('myApp', []) and angular.module('myApp').
This creates the module 'myApp' and overwrites any existing module named 'myApp':
angular.module('myApp', [])
This retrieves an existing module 'myApp':
angular.module('myApp')
I had been overwriting my module in another file, using the first call above which created another module instead of retrieving as I expected.
More detail here: https://docs.angularjs.org/guide/module
I just migrate to angular 1.3.3 and I found that If I had multiple controllers in different files when app is override and I lost first declared containers.
I don't know if is a good practise, but maybe can be helpful for another one.
var app = app;
if(!app) {
app = angular.module('web', ['ui.bootstrap']);
}
app.controller('SearchCtrl', SearchCtrl);
I had this problem when I accidentally redeclared myApp:
var myApp = angular.module('myApp',[...]);
myApp.controller('Controller1', ...);
var myApp = angular.module('myApp',[...]);
myApp.controller('Controller2', ...);
After the redeclare, Controller1 stops working and raises the OP error.
Really great advise, except that the SAME error CAN occur simply by missing the critical script include on your root page
example:
page: index.html
np-app="saleApp"
Missing
<script src="./ordersController.js"></script>
When a Route is told what controller and view to serve up:
.when('/orders/:customerId', {
controller: 'OrdersController',
templateUrl: 'views/orders.html'
})
So essential the undefined controller issue CAN occur in this accidental mistake of not even referencing the controller!
This error might also occur when you have a large project with many modules.
Make sure that the app (module) used in you angular file is the same that you use in your template, in this example "thisApp".
app.js
angular
.module('thisApp', [])
.controller('ContactController', ['$scope', function ContactController($scope) {
$scope.contacts = ["abcd#gmail.com", "abcd#yahoo.co.in"];
$scope.add = function() {
$scope.contacts.push($scope.newcontact);
$scope.newcontact = "";
};
}]);
index.html
<html>
<body ng-app='thisApp' ng-controller='ContactController>
...
<script type="text/javascript" src="assets/js/angular.js"></script>
<script src="app.js"></script>
</body>
</html>
If all else fails and you are using Gulp or something similar...just rerun it!
I wasted 30mins quadruple checking everything when all it needed was a swift kick in the pants.
If you're using routes (high probability) and your config has a reference to a controller in a module that's not declared as dependency then initialisation might fail too.
E.g assuming you've configured ngRoute for your app, like
angular.module('yourModule',['ngRoute'])
.config(function($routeProvider, $httpProvider) { ... });
Be careful in the block that declares the routes,
.when('/resourcePath', {
templateUrl: 'resource.html',
controller: 'secondModuleController' //lives in secondModule
});
Declare secondModule as a dependency after 'ngRoute' should resolve the issue. I know I had this problem.
I was getting this error because I was using an older version of angular that wasn't compatible with my code.
These errors occurred, in my case, preceeded by syntax errors at list.find() fuction; 'find' method of a list not recognized by IE11, so has to replace by Filter method, which works for both IE11 and chrome.
refer https://github.com/flrs/visavail/issues/19
This error, in my case, preceded by syntax error at find method of a list in IE11. so replaced find method by filter method as suggested https://github.com/flrs/visavail/issues/19
then above controller not defined error resolved.
I got the same error while following an old tutorial with (not old enough) AngularJS 1.4.3. By far the simplest solution is to edit angular.js source from
function $ControllerProvider() {
var controllers = {},
globals = false;
to
function $ControllerProvider() {
var controllers = {},
globals = true;
and just follow the tutorial as-is, and the deprecated global functions just work as controllers.
I'm getting this error when I try to attach a service to a controller:
[$injector:unpr] ... webSocketServiceProvider <- webSocketService <- videoMenuCtrl
I have a plunker defined with a fairly minimal setup that reproduces the problem:
http://plnkr.co/edit/ptaIaOhzOIG1mSi4bPyF?p=preview
Here are the main culprit files:
index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>title</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body ng-app="videoApp">
<section class="menu" ng-controller="videoMenuCtrl">
</section>
<script src="webSocketService.js"></script>
<script src="videoMenu.js"></script>
<script src="ngDialog.min.js"></script>
<script src="ngPopup.min.js"></script>
</body>
</html>
webSocketService.js:
(function(angular) {
'use strict';
angular.module('videoApp')
.factory('webSocketService', function($q) {
return{};
});
});
videoMenu.js:
'use strict';
var app = angular.module('videoApp', ['ngDialog', 'ngPopup']);
app.controller('videoMenuCtrl', function($scope, $window, $location, ngDialog, webSocketService) {
});
I don't get an error if I remove the webSocketService from the controller, but the point is to have the controller be able to access the webSocketService. Any ideas? Thanks!
Edit: Changed file name typo.
I got your code working. Two things I noticed:
In you webSocketService.js you were re-declaring the videoApp module.
You were declaring the module inside a function expression that was not being invoked.
I re-declared your service in a properly namespaced module and wrapped it in an immediately invoked function expression.
I also removed your var app = declaration from your videoMenuCtrl and wrapped it in an IIFE as well. This is to avoid cluttering the global namespace. Here is a working plunk:
http://plnkr.co/edit/A8BcATiaqhXCA7BZDXWx?p=preview
EDIT (clarification) The IIFEs are not strictly necessary in my example plunk because the var app = declaration was removed from the code. That was the only variable that was being declared on the global namespace in the original example. However, wrapping the code in IIFEs has no negative effects as far as I know.
Let's say, I have HTML like this
<html ng-app='CoreAngular_App'>
<script>
var CoreAngular_AppObj = angular.module('CoreAngular_App', ['importantModule1', 'importantModule2', 'customModule1', 'customModule2', 'customModule3']);
</script>
<!-- here goes html structure with lot of ng-controller -->
<script>
//controller example
CoreAngular_AppObj.controller('MyControllerX', function($scope, myCustomModule2) {
}
</script>
</html>
It works, but as I have a lot of controllers and I don't know which of them will used, I want to load this list ['customModule1', 'customModule2', 'customModule3'] dynamically
I will glad to get something like this.
<html ng-app='CoreAngular_App'>
<script>
var CoreAngular_AppObj = angular.module('CoreAngular_App', ['importantModule1', 'importantModule2']);
</script>
<!-- here goes html structure with lot of ng-controller -->
<script>
// ADD myCustomModule2 TO CoreAngular_AppObj HERE
//controller example
CoreAngular_AppObj.controller('MyControllerX', function($scope, myCustomModule2) {
}
</script>
</html>
Is it possible? And how?
Thanks
I'll try to make an example of what either may look like.
Inline - from backend logic -
// Create list from rendered array.
var modules = ['customModule1', 'customModule3']; // ex: print json_encode($arrayStr);
// Add a custom module
angular.module('myCustom', modules);
//Inject the custom module
angular.module('CoreApp', ['importantModule1', 'importantModule2', 'myCustom']);
angular.bootstrap docs
Remember to remove ng-app
var app = angular.module('CoreApp', []);
someReadyFunction(){
// figure out which moules here
angular.bootstrap(document, ['CoreApp', 'customModule1', 'customModule3']);
}