I have a part in my angular application on which I've binded a controller,
since then I got the Argument 'fn' is not a function Error, can anyone look at my code and explain why I got that Error?
I would be very gratefull :)
html-markup:
<section class="col-lg-12" data-ng-controller="MessageController">
<fieldset>
<legend>{{ 'MESSAGES' | translate }}</legend>
</fieldset>
<div class="margin-left-15">
<ul class="list-style-button">
<li data-ng-repeat="message in MSG">{{ message }}</li>
</ul>
</div>
</section>
controller:
(function() {
'use strict';
var controllers = angular.module('portal.controllers');
controllers.controller('MessageController', ['$scope', 'MessageService', '$rootScope', function MessageController($scope, MessageService, $rootScope) {
$rootScope.MSG = MessageService.getMessages();
$rootScope.$watch('MSG', function(newValue) {
$scope.MSG = newValue;
});
}]);
}());
Service:
(function() {
'use strict';
var messageServices = angular.module('portal.services');
messageServices.factory('MessageService', ['MessageData', 'localStorageService', 'UserService'], function(MessageData, localStorageService, UserService) {
return new MessageService(MessageData, localStorageService, UserService);
});
function MessageService(MessageData, localStorageService, UserService) {
this.messageData = MessageData;
this.localStorageService = localStorageService;
this.userService = UserService;
}
MessageService.prototype.getMessages = function() {
var locale = this.userService.getUserinfoLocale();
var messages = this.localStorageService.get(Constants.key_messages + locale);
if (messages !== null && messages !== undefined) {
return JSON.parse(messages);
} else {
return this.messageData.query({
locale: locale
}, $.proxy(function(data, locale) {
this.save(Constants.key_messages + locale, JSON.stringify(data));
}, this));
}
};
MessageService.prototype.save = function(key, value) {
this.localStorageService.add(key, value);
};
}());
data:
(function() {
'use strict';
var data = angular.module('portal.data');
data.factory('MessageData', function($resource) {
return $resource(Constants.url_messages, {}, {
query: {
method: 'GET',
params: {
locale: 'locale'
},
isArray: true
}
});
});
}());
order of js files in html head:
<script src="js/lib/jquery-1.10.js"></script>
<script src="js/lib/angular.js"></script>
<script src="js/lib/angular-resource.js"></script>
<script src="js/lib/angular-translate.js"></script>
<script src="js/lib/angular-localstorage.js"></script>
<script src="js/lib/jquery-cookies.js"></script>
<script src="js/lib/bootstrap.js"></script>
<script src="js/portal.js"></script>
The problem was in using the 'wrong' syntax to create the service
instead of using:
messageServices.factory('MessageService',
['MessageData','localStorageService', 'UserService'],
function(MessageData, localStorageService, UserService){
return new MessageService(MessageData, localStorageService, UserService);
}
);
I had to use:
messageServices.factory('MessageService',
['MessageData','localStorageService', 'UserService',
function(MessageData, localStorageService, UserService){
return new MessageService(MessageData, localStorageService, UserService);
}
]);
I closed the array with parameters to soon, and since I'm still learning I didn't see it directly, anyhow I hope I can help others who stumble upon this.
Today I got the same kind of error doing that silly mistake:
(function(){
angular
.module('mymodule')
.factory('myFactory', 'myFactory'); // <-- silly mistake
myFactory.$inject = ['myDeps'];
function myFactory(myDeps){
...
}
}());
instead of that:
(function(){
angular
.module('mymodule')
.factory('myFactory', myFactory); // <-- right way to write it
myFactory.$inject = ['myDeps'];
function myFactory(myDeps){
...
}
}());
In fact the string "myFactory" was brought into the injector who was waiting for a function and not a string.
That explained the [ng:areq] error.
The above answers helped me considerably in correcting the same issue I had in my application that arose from a different cause.
At built time, my client app is being concatenated and minified, so I'm writing my Angular specifically to avoid related issues. I define my config as follows
config.$inject = [];
function config() {
// config stuff
}
(I define a function, $inject it as a module and declare what it is).
And then I tried to register the config just as I registered other modules in my app (controllers, directives, etc..).
angular.module("app").config('config', config); // this is bad!
// for example, this is right
angular.module("app").factory('mainService', mainService);
This is wrong, and gave me the aforementioned error. So I changed to
angular.module("app").config(config);
And it worked.
I guess the angular devs intended config to have a singular instance and by so having Angular not accept a name when config is registered.
I had the same issue and In my case the problem was with angular-cookies.js file. It was in folder with other angularjs scripts and when I have used gulp to minify my js files the error occured.
Simple solution was just to place the angular-cookies.js file to another folder, outside the selected folder to minify js files.
My case
let app: any = angular.module("ngCartosServiceWorker"),
requires: any[] = [
"$log",
"$q",
"$rootScope",
"$window",
"ngCartosServiceWorker.registration",
PushNotification
];
app.service("ngCartosServiceWorker.PushNotification");
I forgot to add requires Array as parameters to service like this
app.service("ngCartosServiceWorker.PushNotification", requires);
Related
I have the following code and it works fine:
app.main.js:
angular.module('app', ['ngAnimate', 'ui.router'])
.factory('_', function() {
return window._;
});
angular.module('app').run(['$route', '$rootScope', '$location', function ($route, $rootScope, $location) {
var original = $location.path;
$location.path = function (path, reload) {
if (reload === false) {
var lastRoute = $route.current;
var un = $rootScope.$on('$locationChangeSuccess', function () {
$route.current = lastRoute;
un();
});
}
return original.apply($location, [path]);
};
}]);
bservice:
angular.module('app')
.service('bService', ['$http', '_', function($http, _) { ...
But when I try to separate de factory to a different file I get the Angular Error: $injector:unpr Unknown Provider. This file looks like this:
angular.module('app').factory('_', function() {
return window._;
});
I also made sure that the factory file is included.
Thanks
EDIT
Full error:
Unknown provider: _Provider
I use gulp for the file merges. So everything is in one file.
Gulp didn't like the name factorys. Because of this my factory became damaged in the main .js file.
The solution was to rename the folder to anything els then factorys.
I have the following Angular 1.5 component:
(function () {
'use strict';
angular
.module('EmployeeInformation')
.controller('EmployeeDetailCtrl', EmployeeDetailCtrl)
.component('employeeDetail', EmployeeDetail);
var EmployeeDetail = {
templateUrl: '../views/components/employeeDetail.html',
controller: 'EmployeeDetailCtrl as empdetail',
bindings: {
employee: '<'
}
};
function EmployeeDetailCtrl() { }
})();
Based on the examples on Angular's site, it seems correct to me. However, when I include the file on my page, I get an error saying that it cannot register the component:
[$injector:modulerr] Failed to instantiate module EmployeeInformation due to:
TypeError: Cannot read property 'controller' of undefined
at $CompileProvider.registerComponent [as component]
If I remove the reference to this component, the page loads fine. Does anyone have any idea what I'm doing wrong?
EDIT: I have a service in the same module composed similarly (that is wrapped in a function and without an empty array - see below) that works correctly:
(function () {
'use strict';
angular
.module('EmployeeInformation')
.service('EmployeeService', EmployeeService);
EmployeeService.$inject = ['$http'];
function EmployeeService($http) {
var apiPrefix = 'http://dvlemployees/api/employees';
this.find = find;
this.get = get;
this.getOne = getOne;
function find(queryObj) { }
function get() { }
function getOne(empNumber) { }
})();
EDIT2: Thanks to #Frondor, I figured out the true problem was that I was calling angular.component on the object before I had defined it. Moving the var EmployeeDetail section to the top fixed the problem.
JavaScript
(function(angular) {
'use strict';
angular.module('EmployeeInformation', [])
.controller('EmployeeDetailCtrl', EmployeeDetailCtrl)
.component('employeeDetail', {
templateUrl: 'view.html',
controller: EmployeeDetailCtrl,
bindings: {
hello: '='
}
});
function EmployeeDetailCtrl(){
this.world = 'World!';
}
})(window.angular);
HTML
<body ng-app="EmployeeInformation">
<!-- components match only elements -->
<div ng-controller="EmployeeDetailCtrl as ctrl">
<h1>
<employee-detail hello="'Hello'"></employee-detail>
</h1>
</div>
</body>
view.html
<span>{{$ctrl.hello}} {{$ctrl.world}}</span>
You need to specify an empty array after the module's name, even if you are not using any dependency on your app.
Live example:
http://plnkr.co/edit/8TbRcg5LBsdlqxLkUccJ?p=preview
Try it:
(function (angular) {
'use strict';
angular
.module('EmployeeInformation', [])
.controller('EmployeeDetailCtrl', EmployeeDetailCtrl)
.component('employeeDetail', EmployeeDetail)
;
var EmployeeDetail = {
templateUrl: '../views/components/employeeDetail.html',
controller: 'EmployeeDetailCtrl as empdetail',
bindings: {
employee: '<'
}
};
function EmployeeDetailCtrl() { }
})(angular);
I'm working with AngularJS.
I'd like to get a controller using a first factory which using another one.
It could be schematize like that:
MyCtrl -> Factory1 -> Factory2
So I tried to do in 3 different files (loaded in the following order):
Factory2.js
app.factory('Factory2', function () { ... })
Factory1.js
app.factory('Factory1',['Factory2', function (Factory2) { ... })
controller.js
app.controller('MyCtrl',['$scope', 'Factory1', function ($scope, Factory1) { ... })
And in my HTML I have:
<script src="services/factory2.js" type="text/javascript"></script>
<script src="services/factory1.js" type="text/javascript"></script>
<script src="controllers/controller.js" type="text/javascript"></script>
But it doesn't work and I've got this error Unknown provider: Factory2Provider <- Factory2 <- Factory1
What's wrong with my code? Am I missing something?
You can refactor your codes and use modules, in this way you will not need to use $inject
var app = angular.module('app', ['factories', 'mymodule']);
angular.module('factories', [])
.factory('Factory2', function () { })
.factory('Factory1', ['Factory2', function (Factory2) {
return myCustomFunction = function () {
alert('todo');
}
}]);
angular.module('mymodule', [])
.controller('MyCtrl', ['$scope', 'Factory1', function ($scope, Factory1) {
$scope.text = "testing";
}])
http://jsfiddle.net/kL78rdr3/3/
Why don't you use explicit injection with $inject? It is a better approach, because it gives you more control over the dependencies. For example:
userController.js
function userController (model, routeParams, searchService) {
//implementation
}
userController.$inject = ['$scope', '$routeParams', 'searchService'];
app.controller("userController", userController);
searchService.js
var searchService = function (http, log) {
//implementation
}
searchService.$inject = ["$http", "$log"];
app.factory("searchService", searchService);
This post may be useful: Explicit Dependency Injection
I am new to angulerJS. i have defined a factory to get data from API but when i try to put the factory in a controller i got error.
That is the factory code.
(Function () {
var CategoriesFactory = function($http) {
var factory = {};
factory.getCategorys = function(account_id){
return $http.get('http://localhost:18678/api/Transaction?account_id=2');
};
factory.getTransaction = function(acc_id){
return $http.get('http://localhost:18678/api/Transaction?acc_id=2');
};
factory.getTransactionInCategory = function(category_id, from_date, to_date){
return.$http.get('http://localhost:18678/api/transaction?category='+category_id+'&account=2&from=2015-01- 01&to=2015-12-30');
};
return factory;
};
angular.module('AccApp').factory('CategoriesFactory', CategoriesFactory);
}());
here is the controller.
app.controller('CategoriesController',
function ($scope, $routeParams, $http, CategoriesFactory) {
})
and here is the error.
Unknown provider: CategoriesFactoryProvider <- CategoriesFactory
I guess you must have forgot to inject AccApp into your mai module where you have defined your app.
angular.module("app", ['AccApp']);
Please do something like this.
Hope this helps!
Why are you trying to write angular code in a wierd way ?
The goal of angular is the simplicity
var app = angular.module('AccApp',[]);
app.factory('CategoriesFactory',function($http){// you can cut and paste this factory into a seperate file if you wish
return{
getCategorys:function(account_id){
return $http.get('http://localhost:18678/api/Transaction?account_id=2');
},
getTransaction:function(acc_id){
return $http.get('http://localhost:18678/api/Transaction?acc_id=2');
},
getTransactionInCategory : function(category_id, from_date, to_date){
return.$http.get('http://localhost:18678/api/transaction?category='+category_id+'&account=2&from=2015-01- 01&to=2015-12-30');
};
}
});
Now you can Inject this factory into your controller simply:
app.controller('CategoriesController',function ($scope, $routeParams, $http, CategoriesFactory){
console.log(CategoriesFactory.getCategorys(getCategorys));
});
This post was based on this.
My intention is to separate components on a file basis. For example, I want a specific controller to have it's own file (Same goes with services, filters and directives). Of course, files will be group together based on the module they will fall into. Here's an overview of what I currently have:
Directory
User/
User/UserModule.js
User/UserDirective.js
User/UserService.js
User/UserFilter.js
User/UserController.js
UserModules.js
UserModule = angular.module('UserModule', []);
UserModule.controller('userCtrl', ['$scope', 'UserService', UserCtrl])
.factory('userService', function() {
return new UserService();
})
.filter('userFilter', UserFilter)
.directive('userDirective', UserDirective);
UserController.js
UserCtrl = function($scope, UserService) {
// ...
};
UserDirective.js
UserDirective = function() {
return {
// ...
}
};
UserService.js
UserService = function() {
// ...
};
UserFilter.js
UserFilter = function() {
return function() {
// ...
}
};
Then I'll just push the user module to the app module.
app.requires.push('UserModule');
My concern lies on the registration of the concepts (Such as controllers, services...) to the module. I was wondering if this is the best way to go and if it's correct. Also possible issues on the parameters and the external js file.
Consider this part:
.controller('userCtrl', ['$scope', 'UserService', UserCtrl])
The UserCtrl above refers to a function defined in a separate file. Will I be able to pass the $scope and UserService dependency as parameters to the UserCtrl?
UserCtrl = function($scope, UserService) { // Pass parameters (UserController.js)
What's the correct way of doing this in terms of Services, Filters and Directives?
Finally, how can I improve the code?
I'm also using Meteor btw.
You do not need to declare global variables UserModule, UserDirective, UserService. You just need to declare/register them as below. Angular will take care of injecting dependencies.
UserModule.js
angular.module('UserModule', []);
UserDirective.js
angular.module('UserModule').directive('userDirective', function() {
return {
// ...
}
});
UserService.js
angular.module('UserModule').service('UserService', function() {
});
UserController.js
angular.module('UserModule').controller('UserController', ['$scope', 'UserService', function($scope, UserService){
}])