Error "controller name" is not a function in angular js? - angularjs

I am working with blade template engine. I want to follow a convention of "One Controller per Page" to easily handle code.
I have one JS file which has few controllers which will be used in all files/pages So i included in my template file which will automatically generated in each page.
Code is as follows
angular.module('MyApp',['angularFileUpload'])
.factory('MyFactory', ['$http',function($http) {
return{
get: function(callback){
$http.get('my-url')
.success(function(data) {
callback(data);
});
}
};
}])
.controller('GlobalController',['$scope','$http','MyFactory',function($scope,$http,MyFactory){
SchoolFactory.get(function(data){
console.log(data);
});
// Few Function which will be called in all pages
}]);
Now When create a new page using that template that includes above JS, I get error. Here is what I create new js file.
angular.module('MyApp',[])
.controller('SomeController',['$scope','$http',function($scope,$http){
// Few Function which will be called in all pages
}]);
Any Page which include this module i get error in console that SomeController is not a function.
Please help me. Thanks in advance.

This is same problem which i faced when i started working with Angular JS. Your code has very little error.
You can create multiple angular.module in single page but only one can have dependencies.
angular.module('MyApp',['angularFileUpload'])
angular.module('MyApp')
From your second module remove empty array [].

angular.module('MyApp')
.controller('SomeController',['$scope','$http',function($scope,$http){
// Few Function which will be called in all pages
}]);
Remove the , [] in the module. Any time you pass an array to the module function, it recreates the module. Since you want to add something to an existing module, leave it off.

Related

Angular JS - Sending data from a directive to a parent controller

I have an app where I use the ngCart directive in order to store the items added to a basket. The problem is that this directive just has the functionality of sending the information about the items added by the user, but I would need also to send some information that I would get from a form.
So in order to send it in a single object, I need first to extract the data stored in the directive to my main scope, and then merge it with the data I get from the form.
For that I need to modify the ngCart.js directive. I tried to make a service, as adviced here, but I don't get to get it working. The code I added to the directive is this
.service('ngCartData', ['ngCart', function(ngCart){
return {
data:ngCart;
};
}])
, but I get an error saying Module 'ngCart' is not available!
I'm totally new to services and factories in angular, so I don't know exactly where to look to make it work. I made a plunkr with my code (I tried modifying the ngCart.js file with the code above, but the plunkr shows the directive without any modification). I just need to be able to send the data stored in the directive in the scope ngCart so that I can listen to it in the parent controller (see the checkout section in the plunkr).
Any help would be much appreciated. Thanks!
did you load the js file like this :
<script src="pathto/angular/angular.js"></script>
<script src="pathto/ngCart.js"></script> or ngCart.min.js
did you load the module in your declaration module like this ? :
var myApp = angular.module('myApp',['ngCart']);
You actually have this backward. You can't inject a directive into a service. You must inject the service into the main controller and into the directive so that you can use it as a bridge between the two. Services are singletons so if you modify the properties of a service those modifications will be available anywhere else it is asked for.
Your service will look something like this:
.service('ngCartData', [function(){
return {
data:[],
addData: function(newData){
this.data.push(newData);
},
getData: function(){
return this.data;
}
};
}])
then in your controller and directive use the ngCartData api, which would look something like this:
$scope.someData = ngCartData.getData();
$scope.someFunction = function(dataToStore){
ngCartData.addData(dataToStore);
};
You had the right idea in mind, and I'm surprised it didn't work for you.
I have edited your app in the following way (in script.js)
app.controller('myCtrl', function($scope, ngCart, myCart) {
$scope.names = [...];
...
console.log(myCart.cart);
})
.factory('myCart',function(ngCart){
return {
cart: ngCart.$cart
};
})
and it logged {shipping: 30, taxRate: null, tax: null, items: Array[2]}, which I think is what you need (I added 2 items before it logged).
Notice that adding a the service is redundant; The data is accessible whenever and wherever you need. Just inject ngCart to your controller/service/etc. and the updated data will be available to you.
Therefore, the following code is equivalent:
app.controller('myCtrl', function($scope, ngCart) {
$scope.names = [...];
...
console.log(ngCart.$cart);
});
A possible reason for the getting the error you got might be that, while editing the ngCart module, you had some sort of error (like a typo), which led to ngCart being invisible to angular.

angular-ui: where is the page $scope inside a <script> element? For a google chart

I'm trying to add a chart to code created by others.
I understand a bit of angular, only...
I'm using angular-ui, so I don't have access to the HEAD tag where the simple Google instructions say to put the SCRIPT tags. I tried putting it later in the html, with other SCRIPT tags, but it kept saying "google" was undefined.
Finally, it seems to work if I put it inside the onload function:
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
drawCharts = function() {
var is = issue;
... create the chart using data inside $scope.issue
}
// google.charts.load( -- DOESN'T WORK HERE, google is undefined
$(window).load(function () {
// finally, in here, 'google' is defined
google.charts.load('current', {'packages': ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawCharts);
}
PROBLEM: drawCharts() needs to access the $scope, but here there's no access to $scope, so my angular data isn't accessible and drawCharts() fails.
So somewhere I need to connect
google.charts.setOnLoadCallback() and $scope
How?
I found one question where the person had a:
$rootScope
.$on('$viewcontentLoaded', function(...)
But he has it in main.js, and I don't have a main.js.
I tried putting it in my controller for the page, but it doesn't define $rootScope. I tried adding $rootScope to the parameters passed to the first line of my controller:
people.controller("voterIssueCtrl", function ($rootScope, $scope, $http, $cookieStore, $window, ClIENT
And that took care of the undefined $rootScope, but the $viewContentLoaded function was never called (it just contained a console.log() message...)
Perhaps my app.js is his main.js.
But it references the controller by name, so it probably loads it, so it probably can't reference something the controller defines.
Help?
===============
I pulled a google chart directive from the web
added the tag in index.html to pull it in
and added the directive to my module definition.
(Of course I forgot the 2nd one and the code didn't complain...)
Nothing. But no complaint that Google wasn't known...
Putting in sample data helps.
In the grand style of js and angular, it doesn't complain if the data isn't exactly in the form it needs...
If only Angular2 + Typescript had been invented sooner...

registerModule with dependencies

I'm building an app with MEAN.JS and I'm trying to use a controller from another module. I've found that I can do this with dependency injection:
angular.module(‘MyModule’, [‘Dependency’]);
But the way modules are created in MEAN.JS is:
ApplicationConfiguration.registerModule('MyModule');
And I can't just pass a second parameter to registerModule. So, how should I do this? Do I have to use both methods? Am I doing it wrong?
Example
I want to add a new model: Campaign. Campaigns are created by admins only, but can be seen by the "campaign owner" (another User). The create campaign form should list available Users, so the admin can select the one that's going to be the "owner" of that Campaign.
The problem is, the create campaign form is controlled by CampaignsController, how can I list Users? I've used another controller (UsersController) and thats the problem, it is undefined because we are in the Campaign module.
EDIT:
The problem was grunt autorestarting the app incorrectly:
I moved the controller from one module (folder) to another, but grunt was still trying to load it from the old path, and thus failing: Controller not found. I thought the problem was dependency injection, but you only have to close grunt (Ctrl+C) and run it again. Problem solved.
Anyways, thanks for the answer #gilBirman cause it is correct: there is no need to inject anything with MEANJS.
MEAN.js makes all the modules registered via registerModule available to all other modules in your app by adding it as a dependency to the main app called mean. Here's the part of the MEAN.js source code that does this:
var applicationModuleName = 'mean';
....
// Add a new vertical module
var registerModule = function(moduleName) {
// Create angular module
angular.module(moduleName, []);
// Add the module to the AngularJS configuration file
angular.module(applicationModuleName).requires.push(moduleName);
};
So you're on the right track, however it sounds like you are trying to inject a controller. However, in angular, controllers are not injectable. You can inject services, factories, values, and constants.
First create your own module for example:
angular.module('app.controllers', []) - angular module with controllers.
then add controller to that module:
angular.module('app.controllers', [])
.controller('dashboard.admin.account.controller', ['$scope', ($scope) { .... }]);
then create global module which will bind to your markup:
angular.module('app', [
'app.controllers'
'ui.router',
'ngAnimate'
]);
then bootstrap your global module to markup:
domReady(function () {
angular.bootstrap(document, ['app']);
});
Now you can use your controller.

Structuring RequireJS + AngularJS

I'd like to work with both angularjs and requirejs. Before that, I worked with backbonejs and requirejs. I felt a bit more comfortable with that combination.
I also got the bower-seed from github, but it's too nested for the beginning.
Here's what I don't understand:
Require forces me to bootstrap angular myself.
Therefore I create a module named by my app.
Then I bootstrap that module to the document.
angular.module('app', []);
angular.bootstrap(document, ['app']);
That happens after the document ist ready, which is checked by this function:
angular.element(document).ready(function() { ... bootstraping ... }
So far I get it. But how and at what point do I put the ng-app into the header?
app.js has the function to put all my controllers, routers etc. into the app. By returning all modules I loaded inside the require-module. In my case I only load controllers
///app.js///
define(['angular', 'controller'], function (angular){
return angular.module('app',[
'app.controller',
'app.router'
]);
});
My controller:
define(['index', 'uirouter'], function(controllers){
controllers.controller('homeCtrl', function($scope, $routeParams){
$scope.logId = "testId";
});
});
Each controller puts it's content in a collection inside the index-module
my Index file:
///index///
define(['angular'], function(angular){
return angular.module('app.controllers',[]);
});
The Index file returs the controller-module to every controller-file requiring it. So I have all controllers in one module, by loading different controller-files
Here's my question: is this procedure correct and can I go on loading all angular-modules like this?
Im confused by working with angular-modules and require-modules ... Maybe anyone got a nice instruction in how to set up a angular-require project easily :)
Here's a link to the project:LINK ;)
Maybe anyone could help me a little bit :)
I am experimenting with this example: https://github.com/nikospara/angular-require-lazy
I also mentioned it in this SO question.
It needs work, but it is working; discussion on this topic really interests me.

angular js unknown provider

I'm trying to "customize" the mongolab example to fit my own REST API. Now I'm running into this error and I am not sure what I am doing wrong:
Error: Unknown provider: ProductProvider <- Product
at Error (unknown source)
at http://localhost:3000/js/vendor/angular.min.js:28:395
at Object.c [as get] (http://localhost:3000/js/vendor/angular.min.js:26:180)
at http://localhost:3000/js/vendor/angular.min.js:28:476
at c (http://localhost:3000/js/vendor/angular.min.js:26:180)
at d (http://localhost:3000/js/vendor/angular.min.js:26:314)
This is my controller:
function ProductListCtrl($scope, Product) {
$scope.products = Product.query();
}
and this is the module:
angular.module('productServices', ['ngResource']).
factory('Product', ['$resource', function($resource){
var Product = $resource('/api/products/:id', { }, {
update: { method: 'PUT' }
});
return Product;
}]);
Your code looks good, in fact it works (apart from the calls themselves) when copied & pasted into a sample jsFiddle: http://jsfiddle.net/VGaWD/
Hard to say what is going on without seeing a more complete example but I hope that the above jsFiddle will be helpful. What I'm suspecting is that you are not initializing your app with the 'productServices' module. It would give the same error, we can see this in another jsFiddle: http://jsfiddle.net/a69nX/1/
If you are planning to work with AngularJS and MongoLab I would suggest using an existing adapter for the $resource and MongoLab: https://github.com/pkozlowski-opensource/angularjs-mongolab
It eases much of the pain working with MongoLab, you can see it in action here: http://jsfiddle.net/pkozlowski_opensource/DP4Rh/
Disclaimer! I'm maintaining this adapter (written based on AngularJS examples) so I'm obviously biased here.
I got that error because I was passing an incorrect parameter to the factory definition. I had:
myModule.factory('myService', function($scope, $http)...
It worked when I removed the $scope and changed the factory definition to:
myModule.factory('myService', function( $http)...
In case you need to inject $scope, use:
myModule.factory('myService', function($rootScope, $http)...
I just had a similar problem.
The error said the same the in the question, tried to solve it with the answer of pkozlowski.opensource and Ben G, which both are correct and good answers.
My problem was indeed different with the same error:
in my HTML-Code I had the initialisation like this...
<html ng-app>
A bit further down I tried to do something like this:
<div id="cartView" ng-app="myApp" ng-controller="CartCtrl">
I got rid of the first one... then it worked... obviously you can't initialise ng-app twice or more times. fair enough.
I totaly forgot about the first "ng-app" and got totaly frustrated. Maybe this is gonna help someone oneday...
Make sure your main app.js includes the services on which it depends. For example:
/* App Module */
angular.module('myApp', ['productServices']).
.....
pkozlowski's answer is correct, but just in case this happens to someone else, I had the same error after creating the same module twice by mistake; the second definition was overriding the provider of the first:
I created the module by doing
angular.module('MyService'...
).factory(...);
then a bit further down in the same file:
angular.module('MyService'...
).value('version','0.1');
The correct way of doing this is:
angular.module('MyService'...
).factory(...).value('version','0.1');
In my case, I've defined a new provider, say, xyz
angular.module('test')
.provider('xyz', function () {
....
});
When you were to config the above provider, you've to inject it with Provider string appended --> xyz becomes xyzProvider.
Ex:
angular.module('App', ['test'])
.config(function (xyzProvider) {
// do something with xyzProvider....
});
If you inject the above provider without the 'Provider' string, you'll get the similar error in OP.
At the end of the JS file to close the factory function I had
});
instead of
}());
This took me way too long to track down. Make sure you minisafe your controller within your directive.
.directive('my_directive', ['injected_item', function (injected_item){
return {
controller: ['DO_IT_HERE_TOO', function(DO_IT_HERE_TOO){
}]
}
}
Hope that helps
To add my own experience in here, I was trying to inject a service into one of my module config functions. This paragraph from the docs which I eventually found explains why that doesn't work:
During application bootstrap, before Angular goes off creating all services, it configures and instantiates all providers. We call this the configuration phase of the application life-cycle. During this phase, services aren't accessible because they haven't been created yet.
Meaning you can inject providers into module.config(...) functions, but you can't inject services, for that you need to wait until module.run(...), or expose a provider you can inject to module.config
For me, this error was caused by running the minified version of my angular app. Angular docs suggest a way to work around this. Here is the relevant quote describing the issue, and you can find the suggested solution in the docs themselves here:
A Note on Minification
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.
Since this is the top result for "angularjs unknown provider" on Google right now, here's another gotcha. When doing unit testing with Jasmine, make sure you have this statement in your beforeEach() function:
module('moduleName');
Otherwise you'll get this same error in your tests.
Yet another case where this error will occur, if you're service is defined in a separate javascript file, make sure you reference it! Yes, I know, rookie mistake.
I was forgetting to inject the file that held my services altogether. Remember to do this when initializing your app module:
angular.module('myApp', ['myApp.services', ... ]);
In my case, I used an anonymous function as a wrapper for the angular module, like this:
(function () {
var app = angular.module('myModule', []);
...
})();
After closing the parenthesis, I forgot to call the anonymous function by opening and closing the parentheses again as above.
For me the problem was lazy loading; I loaded my controller and service late, so they were not available at page load (and Angular initialization). I did this with an ui-if tag, but that's irrelevant.
The solution was to load the service with the page load already.
Here's another possible scenario where you can see this error:
If you use Sublime Text 2 and the angular plugin, it will generate stubs like this
angular.module('utils', [])
.factory('utilFactory', [''
function() {
return {
}
}
]);
notice the empty ' ' as the first element of the array after the 'utilFactory' string. If you don't have any dependencies, remove that so it's like this:
angular.module('utils', [])
.factory('utilFactory', [
function() {
return {
}
}
]);
Since this question is top google result, I will add another possible thing to the list.
If the module that you're using has a failure on the dependency injection wrapper, it will provide this same result. For example copy & paste modules from the internet may rely on underscore.js and attempt to inject with '_' in the di wrapper. If underscore doesn't exist in your project dependency providers, when your controller attempts to reference your module's factory, it will get 'unknown provider' for your factory in the browser's console log.
The problem for me was that there were some new javascript files I created that referenced the service yet Chrome saw only the older version. A CTRL + F5 fixed it for me.
I got an "unknown provider" error related to angular-mocks (ngMockE2E) when compiling my project with Grunt. The problem was that angular-mocks cannot be minified so I had to remove it from the list of minified files.
After handling with this error too, I can support this list of answers with my own case.
It's at the same time simple and dumb (maybe not dumb for beginners like me, but yes for experts), the script reference to angular.min.js must be the first one in your list of scripts in the html page.
This works:
<script src="Scripts/angular.min.js"></script>
<script src="MyScripts/MyCartController.js"></script>
<script src="MyScripts/MyShoppingModule.js"></script>
This not:
<script src="MyScripts/MyCartController.js"></script>
<script src="MyScripts/MyShoppingModule.js"></script>
<script src="Scripts/angular.min.js"></script>
Notice about the angular.min.js.
Hope it helps anyone !! :)
My problem was with Yeoman, using (capitalized):
yo angular:factory Test
Made files (uncapitalized):
app/scripts/services/test.js
but the index.html file included (capitalized):
<script src="scripts/services/Test.js"></script>
Hope this helps someone.
Yet another possibility.
I had unknown Provider <- <- nameOfMyService. The error was caused by the following syntax:
module.factory(['', function() { ... }]);
Angular was looking for the '' dependency.
My scenario may be a little obscure but it can cause the same error and someone may experience it, so:
When using the $controller service to instantiate a new controller (which was expecting '$scope' as it's first injected argument) I was passing the new controller's local scope into the $controller() function's second parameter. This lead to Angular trying to invoke a $scope service which doesn't exist (though, for a while, I actually thought that I'd some how deleted the '$scope' service from Angular's cache). The solution is to wrap the local scope in a locals object:
// Bad:
$controller('myController', newScope);
// Good:
$controller('myController, {$scope: newScope});
None of the answers above worked for me, maybe I was doing completely wrong, but as a beginner that's what we do.
I was initializing the controller in a div in order to have a list:
<div ng-controller="CategoryController" ng-init="initialize()">
And then using $routeProvider to map a URL to the same controller. As soon as I removed the ng-init the controller worked with the route.
I had same problem. I fixed that using $('body').attr("ng-app", 'MyApp') instead of <body ng-app="MyApp"> to boostrap.
Because I did
angular.element(document).ready(function () {
angular.bootstrap(document, [App.Config.Settings.AppName]);
})
for architecture requirements.
In my Ruby on Rails app, I had done the following:
rake assets:precompile
This was done in the 'development' environment, which had minified Angular.js and included it in the /public/assets/application.js file.
Removing the /public/assets/* files solved the problem for me.
I faced similar issue today and issues was really very small
app.directive('removeFriend', function($scope) {
return {
restrict: 'E',
templateUrl: 'removeFriend.html',
controller: function($scope) {
$scope.removing = false;
$scope.startRemove = function() {
$scope.removing = true;
}
$scope.cancelRemove = function() {
$scope.removing = false;
}
$scope.removeFriend = function(friend) {
var idx = $scope.user.friends.indexOf(friend)
if (idx > -1) {
$scope.user.friends.splice(idx, 1);
}
}
}
}
});
If you observe the above block, in the first line you will observe I injected $scope by mistake which is incorrect. I removed that unwanted dependency to solve the issue.
app.directive('removeFriend', function() {
return {
restrict: 'E',
templateUrl: 'removeFriend.html',
controller: function($scope) {
$scope.removing = false;
$scope.startRemove = function() {
$scope.removing = true;
}
$scope.cancelRemove = function() {
$scope.removing = false;
}
$scope.removeFriend = function(friend) {
var idx = $scope.user.friends.indexOf(friend)
if (idx > -1) {
$scope.user.friends.splice(idx, 1);
}
}
}
}
});
I had this error after I created a new factory and used it within a component but I did not check the specs of that components
so if the failure in your (specs) test files
you need to add beforeEach(module('YouNewServiceModule'));
Another 'gotcha': I was getting this error injecting $timeout, and it took a few minutes to realize I had whitespace in the array values. This will not work:
angular.module('myapp',[].
controller('myCtrl', ['$scope', '$timeout ',
function ($scope, $timeout){
//controller logic
}
]);
Posting just in case some else has a silly error like this.
My case was dodgy typing
myApp.factory('Notify',funtion(){
function has a 'c' !

Resources