AngularJS: Routeprovider is not firing routeChangeStart? - javascript

I am trying to get a routeProvider running in an AngularJS app. This seems quite straightforward, but i seem to be missing something - at least my links are not working yet.
I tried to debug my code with firebug, but the routeChangeStart event which i wanted to observe with the following code is not firing.
app.run(['$rootScope',
function($rootScope) {
$rootScope.$on('$routeChangeStart', function(event, next, current) {
var currentPath = current.originalPath;
var nextPath = next.originalPath;
console.log('current: %s; next: %s', currentPath, nextPath);
});
}
]);
Setup:
My index.html contains some links pointing to #/page and a line <div ng-view></div> which should load the content of page.html when a link is clicked.
The app.js file which contains my routeprovider is called correctly in my index.html (Firebug runs through it on pageload).
My routeProvider is setup like this:
angular.module('MyModule', ['ngRoute'])
.config(function($routeProvider) {
$routeProvider
.when("/page", {templateUrl: "partials/page.html", controller: "TestCtrl"})
.when(...);
Is there anything i forgot to get the routeProvider running? I tried to stick as close as possible to the example at https://docs.angularjs.org/api/ngRoute/service/$route and don't really know how i can debug this when there is nothing running that i could debug.

Related

Injecting Angular modules: Unknown provider

I followed a tutorial on how to organize and Angular project. I have a ng directory that contains all my controllers, services and my routes.js. This is then bundled all together into an app.js by my gulp config.
My module.js is like this:
var app = angular.module('app', [
'ngRoute',
'ui.bootstrap'
]);
Here's a bit of my routes.js:
angular.module('app')
.config(function ($routeProvider) {
.when('/login', { controller: 'LoginCtrl', templateUrl: 'login.html'})
});
Here's what my working LoginCtrl looks like:
angular.module('app')
.controller('LoginCtrl', function($scope, UserSvc) {
$scope.login = function(username, password) {
...
}
})
The tutorial didn't make use of any Angular modules and I wanted to try one out. I added ui.bootstrap to my page from a CDN and try to change the LoginCtrl to:
angular.module('app')
.controller('LoginCtrl', function($scope, $uibModal, UserSvc) {
...
})
But this throws me the following error:
"Error: [$injector:unpr] Unknown provider: $templateRequestProvider <- $templateRequest <- $uibModal
What is causing this error? In every tutorial I find this seems to be how they load a module, the only difference I see is that the tutorial don't seem to be using a router.
PS: Note that if I use an empty module list [] I get the exact same error. If I use a non-existing module ['helloworld'] I get an errorModule 'helloworld' is not available'. So I'm concluding that my `ui.bootstrap' module is indeed available.
EDIT: Plunker fiddle here: http://plnkr.co/edit/FWHQ5ZDAByOWsL9YeMUH?p=preview
angular route is another module you should not only include but also use like this
in the app module creation
means DI of route
angular.module('app', ['ngRoute']);
Please go through the angular route doc
Remove ['ui.bootstrap'] form controller. You should add dependencies only one time but you add it twice so the second dependency list override the first one.
angular.module('app')
.controller('LoginCtrl', function($scope, UserSvc) {
... })
your routes snippet looks wrong, you should be hanging the when call off $routeProvider and maybe declare $routeProvider as an injected val if it's not being picked up e.g.
angular.module('app')
.config(["$routeProvider", function ($routeProvider) {
$routeProvider.when('/login', { controller: 'LoginCtrl', templateUrl: 'login.html'})
}]);
I have checked your link. I think there is a serious issue with angular and ui bootstrap version.In ui-boostrap dashboard, it is written that 0.12.0 is the last version that supports AngularJS 1.2.x. I have tried with all combinations but it doesn't work with your angular version.
I suggest you to change angular version to latest and ui-bootstrap version to latest so it will work.
Please check out this working Plukr
<script src='https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular-route.js'></script> //change this to latest also.
<script src='https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/1.0.3/ui-bootstrap.min.js'></script>
<script src='./app.js'></script>
If you want to go with your angular version only. I'd request you to do some R&D. Try with different versions of ui-bootstrap. still if it doesn't work you can make PR.

AngularJS ignore routing by ui.route

I try change build-in Angular route mechanism to ui.router. So I included angular.ui.router.js to my index.html and to my module:
var app = angular.module('multibookWeb', ['ui.router']);
Next I set routing in app.config:
$urlRouterProvider.otherwise('/list');
$stateProvider
.state('list', {
url: '/list',
templateUrl: '/partials/list/list.html',
});
Console don't show any errors, but routing doesn't work. I fired www.someAddress.com/# and I expect that my routing redirects me to www.someAddress.com/#/list or something like this. Unfortunately it doesn't happend. When I console (inside $watch) value of $state.current.name it return me empty string. I tried debugging by this, but console is still empty...
My Angular version: 1.2.28
My Ui.router version: 0.2.13
Here is plunker
The problem is, you have no ui-view.
For the ui-router to function you will need an ui-view. Replace your ng-view with ui-view and it will work.

$routeParams in a controller for index.html

I have an application that only uses an index with a controller main.js. I want the content to be defined by the URL, so I want to use $routeParams in the controller. My problem is that it turns up empty.
This is in my app.js
.config(function ($routeProvider) {
$routeProvider
.when('/:guid', {
templateUrl: '/index.html',
controller: 'MyCollectionUnitCtrl'
})
.otherwise({
redirectTo: '/'
});
});
The controller:
.controller('MyCollectionUnitCtrl',
function ($scope, $location, $routeParams) {
console.log($routeParams.guid); // Undefined
}
I've doubled checked that the module-names are the same.
The problem is that none of the code from the controller runs. I tested this by adding a console.log at the top. Index is not even a template, as I use no partials. I can't find anything about routing when only using one view, so here's where I'm stuck.
It doesn't work when I just define the controller with ng-controller neither.
Ideas? Something I'm missing? Is this a stupid question that's easily explained by documentation? I appreciate all comment, answers and feedback you can give me.
Thank you!
EDIT:
I've also tried to define ng-controller in the index.html, and then only have controller in the routingConfig, but that did not work either.
EDIT2: Plunker
Its hard to find out actual problem with your code snippet, but i think you are missing ngRoute module.
Add angular-route.js script in your html and add ngRoute dependency in your module.

Tried to Load Angular More Than Once

I have a yeoman scaffolded app (the angular fullstack generator).
grunt serve works fine, but grunt build produces a distribution that locks up memory, most probably because of circular references in angular.
I upgraded angular to 1.2.15. The error I get is:
WARNING: Tried to Load Angular More Than Once
Prior to upgrading, the error was:
Error: 10 $digest() iterations reached. Aborting!
It's pretty difficult to debug as it only happens after build / minification. All my modules are in angular's array format, so the minification DI shouldn't be a problem but it is.
There's no single script that causes this. The only way it goes away is if I don't initialize with my app.js file. My app.js file is below.
Any thing come to mind?
'use strict';
angular.module('myApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'ngTagsInput',
'ui.bootstrap',
'google-maps',
'firebase'
]);
angular.module('myApp').config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/listing.html',
controller: 'ListingCtrl'
})
.otherwise({
redirectTo: '/'
});
}]).constant('FIREBASE_URL', 'something');
This could be a number of issues: essentially it's a problem of routeProvider not finding a file and recursively loading the default.
For me, it turned out that it wasn't minification but concatenation of the js that caused the problems.
angular.module('myApp').config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/listing.html',
controller: 'ListingCtrl'
})
.otherwise({
redirectTo: '/'
});
}]).constant('FIREBASE_URL', 'something');
You'll notice that if the app can't find a file (i.e., otherwise), then it will redirect to the root, which in this case loads the templateUrl. But if your templateUrl is wrong, then it will cause a recursion that reloads index.html loading angular (and everything else) over and over.
In my case, grunt-concat caused the templateUrl to be wrong after build, but not before.
The problem could occur when $templateCacheProvider is trying to resolve a template in the templateCache or through your project directory that does not exist
Example:
templateUrl: 'views/wrongPathToTemplate'
Should be:
templateUrl: 'views/home.html'
This doesn't have anything to do with app.js at all. Instead, this warning is logged when you include the Angular JS library more than once.
I've managed to reproduce the error in this JSBin. Note the two script tags (two different versions):
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
Relevant Angular code at GitHub.
Seems like nobody has mentioned this anywhere so here is what triggered it for me:
I had the ng-view directive on my body. Changing it like so
<body layout="column">
<div ng-view></div>
...
</body>
stopped the error.
I was also facing such an issue where I was continously getting an infinite loop and the page was reloading itself infinitely. After a bit of debugging I found out that the error was being caused because, angular was not able to load template given with a particular id because the template was not present in that file.
Be careful with the url's which you give in angular apps. If its not correct, angular can just keep on looking for it eventually, leading to infinite loop!
Hope this helps!
I had the same issue, The problem was the conflict between JQuery and Angular. Angular couldn't set the full JQuery library for itself. As JQLite is enough in most cases, I included Angular first in my web page and then I loaded Jquery. The error was gone then.
In my case I was getting this error while using jquery as well as angular js on the page.
<script src="http://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script>
<script src="js/angular.js" type="text/javascript"></script>
<script src="js/angular-route.js" type="text/javascript"></script>
I removed :
<script src="http://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script>
And the warning disappeared.
Had this problem today and figured I would post how I fixed it. In my case I had an index.html page with:
<body ng-app="myApp" ng-controller="mainController"
<div ng-view></div>
</body>
and in my app.js file I had the following code:
$routeProvider.when('/', {
controller : 'mainController',
templateUrl : 'index.html',
title : 'Home'
}).when('/other', {
controller : 'otherController',
templateUrl : 'views/other.html',
title : 'other'
}).otherwise({
redirectTo : '/'
});
As a result, when I went to the page (base_url/) it loaded index.html, and inside the ng-view it loaded index.html again, and inside that view it loaded index.html again.. and so on - creating an infinite recursive load of index.html (each time loading angular libraries).
To resolve all I had to do was remove index.html from the routProvider - as follows:
$routeProvider.when('/other', {
controller : 'otherController',
templateUrl : 'views/other.html',
title : 'other'
}).otherwise({
redirectTo : '/'
});
I had a similar issue, and for me the issue was due to some missing semicolons in the controller. The minification of the app was probably causing the code to execute incorrectly (most likely the resulting code was causing state mutations, which causes the view to render, and then the controller executes the code again, and so on recursively).
I had that problem on code pen, and it turn out it's just because I was loading JQuery before Angular. Don't know if that can apply for other cases.
Capitalization matters as well! Inside my directive, I tried specifying:
templateUrl: 'Views/mytemplate'
and got the "more than once" warning. The warning disappeared when I changed it to:
templateUrl: 'views/mytemplate'
Correct me, but I think this happened because page that I placed the directive on was under "views" and not "Views" in the route config function.
This happened to me too with .NET and MVC 5 and after a while I realized that within the label on Index.cshtml file:
<div data-ng-view=""></div>
again included as section scripts happens to you. To solve the problem on the server side what I do is return the partial view. Something like:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Login()
{
return PartialView();
}
public ActionResult About()
{
return PartialView();
}
}
I had this same problem ("Tried to Load Angular More Than Once") because I had included twice angularJs file (without perceive) in my index.html.
<script src="angular.js">
<script src="angular.min.js">
I have the same problem, because I have angular two times in index.html:
<script src="https://handsontable.github.io/ngHandsontable/node_modules/angular/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
Note that the warning arises only when html5 mode is true, when my html5 mode was false, I did not see this warning.
So removing the first angular.js solves the problem.
You must change angular route '/'! It is a problem because '/' base url request. If you change '/' => '/home' or '/hede' angular will good work.
For anyone that has this issue in the future, for me it was caused by an arrow function instead of a function literal in a run block:
// bad
module('a').run(() => ...)
// good
module('a').run(function() {...})
In my case I have index.html which embeds 2 views i.e view1.html and view2.html. I developed these 2 views independent of index.html and then tried to embed using route.
So I had all the script files defined in the 2 view html files which was causing this warning. The warning disappeared after removing the inclusion of angularJS script files from views.
In short, the script files angularJS, jQuery and angular-route.js
should be included only in index.html and not in view html files.
Another case is with Webpack which concating angular into the bundle.js, beside the angular that is loaded from index.html <script> tag.
this was because we used explicit importing of angular in many files:
define(['angular', ...], function(angular, ...){
so, webpack decided to bundle it too. cleaning all of those into:
define([...], function(...){
was fixing Tried to Load Angular More Than Once for once and all.
My problem was the following line (HAML):
%a{"href"=>"#", "ng-click" => "showConfirmDeleteModal()"} Delete
Notice that I have a angular ng-click and I have an href tag which will jump to # which is the same page. I just had to remove the href tag and I was good to go.
The problem for me was, I had taken backup of controller (js) file with some other changes in the same folder and bundling loaded both the controller files (original and backup js). Removing backup from the scripts folder, that was bundled solved the issue.
I had this problem when missing a closing tag in the html.
So instead of:
<table></table>
..my HTML was
<table>...<table>
Tried to load jQuery after angular as mentioned above. This prevented the error message, but didn't really fix the problem. And jQuery '.find' didn't really work afterwards..
Solution was to fix the missing closing tag.
I was having the exact same error. After some hours, I noticed that there was an extra comma in my .JSON file, on the very last key-value pair.
//doesn't work
{
"key":"value",
"key":"value",
"key":"value",
}
Then I just took it off (the last ',') and that solved the problem.
//works
{
"key":"value",
"key":"value",
"key":"value"
}

Angular js trigger routing

I have a reset link, which is meant to reset my angular js app...
<a ng-click="resetApp()">reset</a>
I am handling the button press in the main controller...
$scope.resetApp = function(){
if(confirm("You will lose data...")){
$scope.user.reset();
// not sure how to do this in more angular js way
window.location = "/#";
}
}
I am not sure if setting the window.location as I have done is the right way to do things. It works for me, but does not seem like the correct way, and I have not been able to find out ow to do it online.
I have been using the so-called AngularJS way like this, at least the routing is handled by AngularJS rather than browser directly.
function Ctrl($scope, $location) {
$scope.resetApp = function(){
...
$location.url('/');
}
}
The path is what is defined in the Route Provider like this:
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'index.html',
controller: 'Ctrl'
}).
...

Categories