OK I give up! I need some help on this one. I have spent a very long time reading all of the similar questions that have been asked on S/O, and nothing has been able to help my problem.
I'm trying to add a factory to my angularFire application.
I am getting the 'Uncaught Object (anonymous function)' error - Through Chrome inspector I have ascertained more specific error information: https://docs.angularjs.org/error/$injector/nomod?p0=ngLocale%22
here is my HTML Script information:
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.18/angular.js"></script>
<script src="js/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/factories.js"></script>
<script src='https://cdn.firebase.com/js/client/1.0.17/firebase.js'></script>
<script src='https://cdn.firebase.com/libs/angularfire/0.7.1/angularfire.min.js'></script>
here is my controller.js:
legalmvc.controller('FormCtrl','FBRetrieve', function FormCtrl($scope, $location, FBRetrieve, $firebase) {
var url = 'https://legalcitator.firebaseio.com';
var fireRef = new Firebase(url);
$scope.addCase = function () {
$scope.FireBaseCases = new Firebase('https://legalcitator.firebaseio.com/case');
$scope.caseData = {};
var newAuthor = $scope.newAuthor;
var newJournal = $scope.newJournal;
var newArticleName = $scope.newArticleName;
var newYear = $scope.newYear;
if (!newAuthor.length || !newArticleName.length || !newJournal.length || newYear === null ) {
return;
}
newAuthor = $scope.newAuthor.trim();
newJournal = $scope.newJournal.trim();
newArticleName = $scope.newArticleName.trim();
var newCaseRow = $scope.FireBaseCases.child(newAuthor);
newCaseRow.set({
type: 'Case',
author: newAuthor,
journal: newJournal,
articleName: newArticleName,
year: newYear }
);
$scope.newAuthor = '';
$scope.newJournal ='';
$scope.newYear =null;
$scope.newArticleName= '';
};
});
here is my factory.js :
legalmvc.factory('FBRetrieve', function(type){
var biblioRef = new Firebase('https://legalcitator.firebaseio.com/'+type);
biblioRef.on('value', function(data) {
if (data.val() === null) {
return;
}
return data;
});
});
and here is the app.js
var legalmvc = angular.module('legalmvc', ['FBRetrieve','ngRoute']);
Will be deeply, deeply grateful if someone could give me a hand, this thing is giving me an aneurysm!!
Sam
EDIT:
The problem was that i was trying to inject my factory 'FBRetrieve' and an external module. I removed this, and then the problem that I was facing was in this code
legalmvc.factory('FBRetrieve', function(type){
var biblioRef = new Firebase('https://legalcitator.firebaseio.com/'+type);
.....
it seems that you cannot pass 'type' in as a parameter on factory function which will allow you to use this same function on different URLs. Can't say i understand exactly why.
Thanks guys!!
Imho the issue is in: var legalmvc = angular.module('legalmvc', ['FBRetrieve','ngRoute']); remove the FBRetrieveentry. It's not an external module it's your factory.
You most likely wanted to use:
var legalmvc = angular.module('legalmvc', ['firebase','ngRoute']);
And you should inject $firebase instead creating new objects new Firebase, the rationale behind this is explained here: https://docs.angularjs.org/guide/unit-testing
You should not inject your factory on the creation of your module as the factory is registered on the module it already knows it.
Correct me if I'm wrong but module declaration only accept injection of other modules.
So from your code you only have to remove the FBRetrieve injection from the module creation.
It becomes :
var legalmvc = angular.module('legalmvc', ['ngRoute']);
As your factory and your controller are on the same module, it will resolve it when creating your controller.
If your factory was on another module, then you would have :
var factoryModule = angular.module("factoryModule");
factoryModule.factory('FBRetrieve', function(type){
...
}
var legalmvc = angular.module('legalmvc',['factoryModule', 'ngRoute']);
legalmvc.controller('controller',['FBRetrieve', '$scope',
function(FBRetrieve, $scope){
...
}]);
Hope it helps.
Related
hi I try to save in cookies after a web response. Here is my code
angular.module('myApp').controller('SignInController',['WebService',function(WebService, $cookies){
this.formData = {};
this.signIn = function(formData){
WebService.login(formData).then(function successCallback(data){
//console.log("Success callback:"+JSON.stringify(data));
var response = data.data;
var message = response['message'];
if (message == 'Success') {
$cookies.put("id", response['id']);
$cookies.put("number", response['number']);
}else{
}
console.log('Message:'+message+" id:"+ $cookies.get('id'));
},function errorCallback(error){
console.log("Error"+JSON.stringify(error));
});
this.formData = {};
};
}]);
i have included ngCookies as module while creating main angular module. What I'm doing wrong here? Anyone show me correct way. Thank you.
array containing all string of all arguments is good approach to handle dependency injection (DI) after your code is minified.
angularJs use Named_parameter in DI, you can understand how DI works by this blog post.
when you minified you angularJs file, ($http, $scope) converted to (a, b) and DI can't understand them.
$inject is my recommended way to handle this situation. its looks clean. (personal opinion, can be vary).
and try to write code which easily maintainable.
var app = angular.module('myApp', []);
SignInController.$inject = ['WebService', '$cookies'];
app.controller('SignInCtrl', SignInController);
function SignInController(WebService, $cookies){
this.formData = {};
this.signIn = signIn;
function signIn(formData) {
WebService.login(formData)
.then(successCallback, errorCallback);
function errorCallback(error){
console.log("Error"+JSON.stringify(error));
}
function successCallback(data){
var response = data.data;
var message = response['message'];
if (message == 'Success') {
$cookies.put("id", response['id']);
$cookies.put("number", response['number']);
}
}
this.formData = {};
};
I'm reading the book Angularjs Essentials - http://www.goodreads.com/book/show/23139559-angularjs-essentials
I'm trying to follow the code exmaples.
I have this plunker with the code I have
https://plnkr.co/edit/jFK3ooODMChtXJqO7syf?p=preview
locally in chrome I get the error
Error: ng:areq
Bad Argument
Argument 'parkingCtrl' is not a function, got undefined
I'm sure the problem is syntax in 'angular module' bit at the top of either controller.js, services.js or directive.js
Can anyone see what I'm doing wrong or how the stop this error
When you define your service, you had recreated the app again with this syntax angular.module('parking', []) that's why the defined controller is no longer existing after this file loaded. So you can change this to angular.module('parking') as below in services.js file will fix the issue
angular.module('parking').factory("parkingService", function() {
var _calculateTicket = function (car) {
var departHour = new Date().getHours();
var entranceHour = car.entrance.getHours();
var parkingPeriod = departHour - entranceHour;
var parkingPrice = parkingPeriod * 10;
return {
period: parkingPeriod,
price: parkingPrice
};
};
return {
calculateTicket: _calculateTicket
};
});
There are two issues
(i) Change the references as below in plunker
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
(ii) No need to have dependencies injected for the service parkingService, change it as
angular.module('parking').factory("parkingService", function() {
}
DEMO
I don't know what it is about injecting factories, but I am having the most difficult time.
I've simulated what I'm attempting to do via this sample plunk http://plnkr.co/edit/I6MJRx?p=preview, which creates a kendo treelist - it works fine.
I have an onChange event in script.js which just writes to the console. That's also working.
My plunk loads the following:
1) Inits the app module, and creates the main controller myCtrl (script.js)
2) Injects widgetLinkingFactory int myCtrl
3) Injects MyService into widgetLinkingFactory
The order in which I load the files in index.html appears to be VERY important.
Again, the above plunk is NOT the real application. It demonstrates how I'm injecting factories and services.
My actual code is giving me grief. I'm having much trouble inject factories/services into other factories.
For example,
when debugging inside function linking() below, I can see neither 'CalculatorService' nor 'MyService' services. However, I can see the 'reportsContext' service.
(function () {
// ******************************
// Factory: 'widgetLinkingFactory'
// ******************************
'use strict';
app.factory('widgetLinkingFactory', ['reportsContext', 'MyService', linking]);
function linking(reportsContext, MyService) {
var service = {
linkCharts: linkCharts
};
return service;
function linkCharts(parId, widgets, parentWidgetData) {
// *** WHEN DEBUGGING HERE, ***
// I CANNOT SEE 'CalculatorService' AND 'MyService'
// HOWEVER I CAN SEE 'reportsContext'
if (parentWidgetData.parentObj === undefined) {
// user clicked on root node of grid/treelist
}
_.each(widgets, function (wid) {
if (wid.dataModelOptions.linkedParentWidget) {
// REFRESH HERE...
}
});
}
}
})();
A snippet of reportsContext'service :
(function () {
'use strict';
var app = angular.module('rage');
app.service('reportsContext', ['$http', reportsContext]);
function reportsContext($http) {
this.encodeRageURL = function (sourceURL) {
var encodedURL = sourceURL.replace(/ /g, "%20");
encodedURL = encodedURL.replace(/</g, "%3C");
encodedURL = encodedURL.replace(/>/g, "%3E");
return encodedURL;
}
// SAVE CHART DATA TO LOCAL CACHE
this.saveChartCategoryAxisToLocalStorage = function (data) {
window.localStorage.setItem("chartCategoryAxis", JSON.stringify(data));
}
}
})();
One other point is that in my main directive code, I can a $broadcast event which calls the WidgetLinking factory :
Notice how I'm passing in the widgetLinkingFactory in scope.$on. Is this a problem ?
// Called from my DataModel factory :
$rootScope.$broadcast('refreshLinkedWidgets', id, widgetLinkingFactory, dataModelOptions);
// Watcher setup in my directive code :
scope.$on('refreshLinkedWidgets', function (event, parentWidgetId, widgetLinkingFactory, dataModelOptions) {
widgetLinkingFactory.linkCharts(parentWidgetId, scope.widgets, dataModelOptions);
});
I am wasting a lot of time with these injections, and it's driving me crazy.
Thanks ahead of time for your assistance.
regards,
Bob
I think you might want to read up on factories/services, but the following will work:
var app = angular.module('rage')
app.factory('hi', [function(){
var service = {};
service.sayHi = function(){return 'hi'}
return service;
}];
app.factory('bye', [function(){
var service = {};
service.sayBye = function(){return 'bye'}
return service;
}];
app.factory('combine', ['hi', 'bye', function(hi, bye){
var service = {};
service.sayHi = hi.sayHi;
service.sayBye = bye.sayBye;
return service;
}];
And in controller...
app.controller('test', ['combine', function(combine){
console.log(combine.sayHi());
console.log(combine.sayBye());
}];
So it would be most helpful if you created a plunk or something where we could fork your code and test a fix. Looking over your services it doen't seem that they are returning anything. I typically set up all of my services using the "factory" method as shown below
var app = angular.module('Bret.ApiM', ['ngRoute', 'angularFileUpload']);
app.factory('Bret.Api', ['$http', function ($http: ng.IHttpService) {
var adminService = new Bret.Api($http);
return adminService;
}]);
As you can see I give it a name and define what services it needs and then I create an object that is my service and return it to be consumed by something else. The above syntax is TypeScript which plays very nice with Angular as that is what the Angular team uses.
I'm running into a problem trying to setup a fairly simple call using a factory and controller in angularjs. I've been attempting to follow the style guides of John Papa and Todd Motto in setting this up.
First I'm using 2 modules
(function(){
'use strict';
angular.module('app',[
'app.core',
'app.property'
]);
})();
In 'app.core' I define the factory
(function(){
'use strict';
angular.module('app.core')
.factory('dataservice',dataservice);
dataservice.$inject = ['$http','$q'];
function dataservice($http,$q) {
var service = {
getListing: getListing
};
return service;
function getListing() {
var def = $q.defer;
$http.get("http://acme.com/property/1?format=json")
.success(function(data){
service.getListing = data;
def.resolve(data);
});
return def.promise;
}
}
})();
and in 'app.property' I defined the controller
(function(){
'use strict';
angular.module('app.property')
.controller('PropertyCtrl',PropertyCtrl);
PropertyCtrl.$inject = ['dataservice'];
function PropertyCtrl(dataservice) {
var vm = this;
vm.listings = [];
activate();
function activate() {
return getListing().then(function(){});
}
function getListing(){
return dataservice.getListing().then(function(data){
vm.listings = data;
console.log("data is");
console.log(data);
return vm.listings;
});
}
}
})();
the error I get in the console output is
Error: dataservice.getListing(...) is undefined except when I inspect dataservice in chrome I can see
Further on I receive
TypeError: Cannot read property 'then' of undefined
TypeError: def.resolve is not a function
Despite these errors the remote call returns json fine.
Hoping someone with angular chops has an idea on where I went wrong.
You're very close. It should be $q.defer() but you've $q.defer
function getListing() {
var def = $q.defer();
$http.get("http://acme.com/property/1?format=json")
.success(function(data){
service.getListing = data;
def.resolve(data);
});
return def.promise;
}
You have to actually create the modules you are building on:
Put this above your app.property module's objects:
angular.module('app.property', []);
Put this above your app.core module's objects:
angular.module('app.core', []);
You are basically attaching a factory and a controller to modules that don't exist. You are trying to inject modules that don't exist into your primary module.
Here is a plunker showing the issues you were having resolved. Your code has some other issues, but at least it's finding the modules now, which was your original problem.
It should also be noted that mohamedrias is also correct - you had an error in syntax by not putting () on your defer call.
I updated my plunker to include his correction as well.
I want to wrap this https://gist.github.com/nblumoe/3052052 in a module. I just changed the code from TokenHandler to UserHandler, because on every api request I want to send the user ID.
However I get module UserHandler not found in firebug console. Here is my full code: http://dpaste.com/1076408/
The relevent part:
angular.module('UserHandler').factory('UserHandler', function() {
var userHandler = {};
var user = 0;
/...
return userHandler;
});
angular.module('TicketService', ['ngResource', 'UserHandler'])
.factory('Ticket', ['$resource', 'UserHandler',
function($resource, userHandler){
var Ticket = $resource('/api/tickets/:id1/:action/:id2',
{
id1:'#id'
},
{
list: {
method: 'GET'
}
});
Ticket = userHandler.wrapActions( Ticket, ["open", "close"] );
return Ticket;
}]);
Any idea why this happens? How to fix it?
Many has fallen into the same trap. Me included.
The following does not define a new module. It will try to retrieve a module named UserHandler which isn't defined yet.
angular.module('UserHandler')
Providing a (empty) array of dependencies as the second argument will define your module.
angular.module('UserHandler', [])
I am new to javascript and have spent a couple of hours to discover my issue. The module initialization function can be ignored. To avoid this, do not forget to add empty parenthesis to the end of a function:
(function() {
"use strict";
var app = angular.module("app", []);
})(); //<<---Here
Also, don't forget to add the new module in your index.html:
<script src="app/auxiliary/test.module.js"></script>
<script src="app/auxiliary/test.route.js"></script>
<script src="app/auxiliary/test.controller.js"></script>