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
Related
When i try to create angularjs module in usual way, it works perfect, but when i try to execute same code inside a callback function of aync function call, it throws error that module not found:
The following code works fine:
var myApp = angular.module('SSApp',[]);
myApp.controller('config', function($scope) {
});
But following throws error:
Init_Data(function() {
initApp();
});
function initApp() {
var myApp = angular.module('SSApp',[]);
myApp.controller('config', function($scope) {
});
}
function Init_Data(callback) {
chrome.storage.local.get(null, function(data) {
window.data = data;
callback();
});
}
I've defined ng-app="SSApp" directive in respective html code.
The reason your code is not doing what you expect is because, Angular tries to bootstrap the module "SSApp" automatically when the DOM is ready. But, finds no such module defined by your JavaScript code when it tries to do so.
You probably have ng-app="SSApp" somewhere in your HTML which is why Angular tries to bootstrap the module automatically.
You can choose to bootstrap the module manually by removing the ng-app directive and doing
angular.bootstrap(document.documentElement, ['SSApp']);
This is the change you have to do:
var myApp = angular.module("SSApp", []);
Init_Data(function () {
initApp();
});
function initApp() {
myApp.controller('config', function ($scope) {
});
console.log(myApp)
}
function Init_Data(callback) {
setTimeout(function () {
callback();
},4000);
}
From what I understand in your code, first you want to load data and then to add config controller to your app...so define your app first and then in your callback configure
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.
Just starting out with AngularJS. Trying to build a single page app to display slides/pages of my comic, one at a time.
The data is getting pulled in from a JSON file, and that's working correctly. But Angular is throwing errors when I try to set up some basic binding. Any thoughts..?
HTML
<span ng-bind-html="showCurrentTitle"></span>
JS
var comicsApp = angular.module('comicsApp', ['ngSanitize']);
comicsApp.controller('comicsCtrl', ['$scope', '$http',
function comicsCtrl($scope, $http) {
$http.get('/luv-slimline/test/comics.json').success(function(data) {
$scope.comics = data.comics;
});
$scope.showCurrentTitle = function() {
return $scope.comics[0].title;
}
} //end ComicsCtrl
]);
Error
TypeError: Object function () { return $scope.comics[0].title; } has no method 'indexOf'
If I strip out the ngSanitize module, then the error message changes.
Alt error
Error: [$sce:unsafe] http://errors.angularjs.org/undefined/$sce/unsafe
And if I swap out the ng-bind-html directive for the older-style mustache braces, then the error message changes again.
Alt error (2)
Error: [$interpolate:interr] http://errors.angularjs.org/undefined/$interpolate/interr?p0=%7B%7BshowCurr…()%7D%7D&p1=TypeError%3A%20Cannot%20read%20property%20'0'%20of%20undefined
Help, please?
Cheers,
Dan
I'm not familiar with the errors you are receiving, or ng-sanitize or the ng-bind-html tag. However, your javascript code looks problematic to me.
var comicsApp = angular.module('comicsApp', ['ngSanitize']);
comicsApp.controller('comicsCtrl', ['$scope', '$http',
function comicsCtrl($scope, $http) {
//so this runs immediately, but . . .
$http.get('/luv-slimline/test/comics.json').success(function(data) {
// . . . this is going to happen async, so this value won't be set
//before the initial binding occurs
$scope.comics = data.comics;
});
$scope.showCurrentTitle = function() {
// . . . as a result, comics will be undefined initially.
return $scope.comics[0].title;
}
} //end ComicsCtrl
]);
I think you need to define an initial value for $scope.comics before your http.get. Something like:
$scope.comics = [];
$scope.comics.push({title: "testTitle"});
Edit
Based on your comment, if you are now just binding to showCurrentTitle (which I would rename to currentTitle, as it makes more sense), you shouldn't even need to initialize $scope.comics--it should work without that code.
Generally, I'd do the following and there would be an ng-app in my HTML:
var myApp = angular.module("myApp", []);
myApp.controller("AttributeCtrl", function ($scope) {
$scope.master = {
name: "some name"
};
});
However, I need to manually bootstrap angular because I'm only using it in a part of my app that is loaded via jQuery's $.load(). If I do the following:
main.js - this is where the page I want to use angular on is being pulled in
$("#form").load(contextPath + url, params, function() {
angular.bootstrap($("#angularApp"));
});
And then the page being pulled in has it's own javascript:
function AttributeCtrl($scope) {
$scope.master = { name: "some name"};
}
This works, however, ideally, I'd like my controllers to be scoped at the module level. So I modified the above code like so
main.js
$("#form").load(contextPath + url, params, function() {
angular.bootstrap($("#angularApp", ["myApp"]));
});
and then...
var app = angular.module("myApp"); // retrieve a module
app.controller("AttributeCtrl", function($scope) {
$scope.master = { name: "some name"};
});
Retrieving the module this way doesn't seem to work, though. Am I doing something wrong?
You cannot create a controller after you've bootstrapped the app. See the documentation for angular.bootstrap.
You should call angular.bootstrap() after you've loaded or defined your modules. You cannot add controllers, services, directives, etc after an application bootstraps.
I don't know if this is just in the example code you have here but:
angular.bootstrap($("#angularApp", ["myApp"]));
should be
angular.bootstrap($("#angularApp"), ["myApp"]);
Your code for retrieving the module should work.
Updated
They updated the documentation and now it reads like this
Each item in the array should be the name of a predefined module or a
(DI annotated) function that will be invoked by the injector as a run
block. See: {#link angular.module modules}
It seems a bug.
The way you implemented to retrieve the module is correct. Just quote it from the doc to make it clear since it may not be well-known.
When passed two or more arguments, a new module is created. If passed
only one argument, an existing module (the name passed as the first
argument to module) is retrieved.
For the problem you mentioned, long story short...
The bootstrap function calls createInjector with the module list ['ng', ['ngLocale', function(){...}] , 'myApp'] (the last one is the module you passed in)
function bootstrap(element, modules) {
...
var injector = createInjector(modules);
Inside createInjector(), it calls loadModules for each module passed in
function createInjector(modulesToLoad) {
forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
And loadModules calls angularModule, which is initialized as angularModule = setupModuleLoader(window);, which creates the object window.angular.module
function loadModules(modulesToLoad){
....
var moduleFn = angularModule(module); // triggers the error
The the error occurs, since angularModule takes 2nd parameter as requires. Without it, it will throws an exception on this line (line 1148) throw Error('No module: ' + name);
Reported: https://github.com/angular/angular.js/issues/3692
Not sure if this counts as a bug or an implementation decision (albeit a seemingly poor one). Adding an empty array solves the undefined require problem that you were having and should solve your problem overall.
var app = angular.module("myApp", []); // create a module
app.controller("AttributeCtrl", function($scope) {
$scope.master = { name: "some name"};
});`
Also, in your fiddle you call {{name}} which won't render. You should be calling {{master.name}}
Edit
Thank you all for the downvotes .. Here's a working example. Good luck!
http://plnkr.co/edit/UowJpWYc1UDryLLlC3Be?p=preview
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>