I am working on an OnsenUI Cordova application, using OnsenUI 1.3.1 (installed via bower), AngularJS 1.3.15, and Cordova 5.0.0. I'm having trouble getting to the ons-navigator object within JavaScript, and all of the methods mentioned in the OnsenUI website for doing so (http://onsen.io/guide/overview.html#CallingComponentAPIsfromJavaScript) don't seem to work for me. I have my code set up as follows:
index.html:
...
<body>
<div ng-controller="MainController">
<ons-navigator id="navigator" var="myNavigator" page="{{targetPage}}">
<div>
Hello!
</div>
</ons-navigator>
</div>
...
</body>
...
MainController:
angular.module('myApp.controllers')
.controller('MainController', ['$log', '$scope',
function ($log, $scope) {
$scope.initialize = function () {
$scope.targetPage = 'views/login.html';
$log.info('scope navigator: ' + $scope.myNavigator); // comes back as undefined
$log.info('find navigator: ' + ons.findComponent('ons-navigator#navigator', document.body)); // comes back as null
};
$scope.initialize();
}]);
I'm currently not outputting the methods outlined in the OnsenUI documentation that utilize the ons.findParentComponentUntil() method or the one that involves changing the component based object, but I have looked into those, and they don't seem to work either (comes back undefined).
Does anyone have any ideas? Thanks!
You are trying to access the navigator element before it has been created, try to execute your code with ons.ready();, for example:
ons.ready(function() {
console.log("scope navigator: " + $scope.myNavigator);
});
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 using a filter with angular typeahead to append an extra item onto the typeahead suggestion list like so:
app.filter('finalAppend', function($sce){
return function(array, value){
array.push({
name: $sce.trustAsHtml('Look for <b>' + value + '</b> in other shops'),
type: 'good'
});
return array;
}
});
I want to return html encoded string, but angular automatically sanitizes it. I tried using $sce as suggested, but it doesn't seem to work. Here's the plunkr: plunkr
thanks in advance.
It seems in ui-bootstrap 0.7.0, there is a conflict between typehead highlight filter and your own finalAppend filter.
Just change your tpl.html to this :
<div ng-if="match.model.type!=null">
<span ng-bind-html="match.label"></span>
</div>
And load angular sanitize to prevent secure error automatically been thrown by angular.
<script src="http://code.angularjs.org/1.3.1/angular-sanitize.js"></script>
inject ngSanitize into your app.
var app = angular.module('myApp', ['ui.bootstrap', 'ngSanitize']);
And it works. Here is the plunker address.
However, if you still want to use the typeahead inner highlight filter, you can change you ui-bootstrap to this(Already change it in the demo):
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.11.2.js"></script>
Hope this can work. Enjoy it. : )
I have a scenario where I need to dynamically load an Angular JS application. I have based the code on this:-
https://stackoverflow.com/a/15252490/1545858
Now, I have code that works really well with angular js 1.1.5, but in 1.2.1, no such luck.
Here is the JS code:-
$("#startMeUp").click(function() {
// Make module Foo
angular.module('Foo', []);
// Make controller Ctrl in module Foo
angular.module('Foo').controller('Ctrl', function($scope) {
$scope.data = {};
$scope.data.name = 'KDawg';
$scope.destroy = function() {
$scope.$destroy();
$('#Ctrl').remove();
};
$scope.$on("$destroy", function () {
console.log("EXTERMINATE");
});
});
// Load an element that uses controller Ctrl
$('<div ng-controller="Ctrl" id="Ctrl"> ' +
'<input type="text" ng-model="data.name"></input>' +
'{{data.name}}' +
'<button ng-click="destroy()">Destroy Me</button></div>').appendTo('#container');
// Bootstrap with Foo
angular.bootstrap($('#Foo'), ['Foo']);
});
And here is the HTML:-
<button id="startMeUp">Start Me Up!</button>
<div id="Foo">
<div id="container">
</div>
</div>
Now, if you start and destroy and start again with angular js 1.1.5, everything works fine, but in angular js 1.2.1 it does not work in on the second start. Any thought on how to make it work in 1.2.1?
Here is the js fiddle:-
http://jsfiddle.net/Y9wj2/
As charlietfl says, you don't need to bootstrap more than once. In fact, using angular.js 1.2.1, the error generated that breaks everything is telling you exactly that:
[ng:btstrpd] App Already Bootstrapped with this Element ''
You should think carefully about whether you really need this controller to be dynamic. If you can just use something like ng-include to load the extra content then you will have a much easier time and no need to worry about compiling the content.
If you find you really do need to take this HTML and load it from outside of angular context then you can use the $compile service. Bootstrap the app once somewhere first, preferably using ng-app and grab the injector.
var injector = angular.bootstrap($('#Foo'), ['Foo']);
or
<div id="Foo" ng-app="Foo"></div>
var injector = $('#Foo').injector();
Now you can insert the HTML however you like and then compile and link it using
injector.invoke(['$compile', '$rootScope', function($compile, $rootScope) {
$compile(insertedJqLiteNode)($rootScope);
});
I wanted to try out the example discussed in http://www.youtube.com/watch?v=HCR7i5F5L8c#t=587
I included 1.0.8 angular js and tried and it flung an error as
Argument 'UserCtrl as uCtrl' is not a function, got undefined
so i thought aliasing was a problem and thought of removing aliasing and changed code to
index.html
<html ng-app>
<body ng-controller='UserCtrl'>
Hi <input ng-model='UserCtrl.user.first'>
<button ng-click='UserCtrl.bye()'>bye</button>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js'></script>
<script src='UserControllers.js'></script>
</body>
</html>
UserControllers.js
function UserCtrl() {
this.user = {
first:'Larry',
last:'Page'
};
this.bye = function() {
alert('bye:' + this.user.first);
};
}
then the above mentioned error went off . But still what is mentioned in that video doesn't happen .I even checked in console and found no errors. The alert is not coming on clicking bye button.
I tried with angular js 1.0.7 and 1.0.8
Please help me to find the problem .
The controller "as" experimental feature was added in 1.1.5 so you're right that was causing issues.
Without "as" the controller is implicit so you don't need to prefix your variable names with it.
So you can either update to 1.1.5 or newer and stick with his use of "as" or here's a version of the code that works on earlier versions of Angular (fiddler here: http://jsfiddle.net/PDqbb/):
<body ng-app ng-controller='UserCtrl'>
Hi <input ng-model='user.first'>
<button ng-click='bye()'>bye</button>
</body>
function UserCtrl($scope) {
$scope.user = {
first:'Larry',
last:'Page'
};
$scope.bye = function() {
alert('bye:' + this.user.first);
};
}
Also, here's a nice overview on "as", which includes a bit on the use of "this" as it applies here: http://www.thinkster.io/pick/GmI3KetKo6/angularjs-experimental-controller-as-syntax