Angular new router error Cannot read property 'path' of undefined - javascript

I'm trying to write an app in angularjs by using the new router. But, don't know what's i'm doing wrong. From two days i went through a lot of articles,videos but till now can't able to get a grip on this.
Right now, i'm following this article - http://goo.gl/ayPmxr . My folder setting is like this..
- components
-- home
--- home.html
- angular.js
- app.js
- index.html
- router.es5.js
My Files -
index.html
Test new router
<body ng-app="app" ng-controller="AppController">
<!-- Multiple viewports require a name -->
<div ng-viewport="nav"></div>
<div ng-viewport="main"></div>
<script type="text/javascript" src="angular.js"></script>
<script type="text/javascript" src="router.es5.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
app.js
Chrome Console error
Can any one please help me to find out where I'm doing wrong & how I can fix that.

That's because you are not specifying any component for the nav viewport/outlet.
You should either remove from your view
<div ng-viewport="nav"></div>
or specify a component in your routes, something like
components: { 'nav': 'home', 'main': 'home' }
It's a known behavior/bug: https://github.com/angular/router/issues/207

As of 2016-01-12, the following works for me:
(just the body of index.html):
<body ng-app="app" ng-controller="AppController">
<ng-viewport></ng-viewport>
<script src="/node_modules/angular/angular.js"></script>
<script src="/node_modules/angular-new-router/dist/router.es5.js"></script>
<script src="./app.js"></script>
<script src="./components/home/home.js"></script>
</body>
// app.js
// This example works as of 2016-01-12 using
// angular 1.5.0-rc.0
// angular-new-router 0.5.3
// Assumes:
// 1. app.js is in the root of the folder structure
// 2. components/home/ folder exists off the root and contains:
// a. home.js
// b. home.html
angular.module('app', ['ngNewRouter', 'app.home'])
.controller('AppController', ['$router', AppController]);
function AppController ($router) {
console.log('made it to AppController');
$router.config([
{path: '/', component: 'home' }
]);
}
I can post home.js and home.html, if needed, but based on the question, the problem is within app.js.
One key difference I spot right away is my (perhaps simplistic) example does NOT enclose the route confiuration inside of a components {} object.
Hope this helps.

Related

Issues With Angular ngRoute

I have spent hours and hours searching and googling to find out why my ngRoute is not working but couldn't find the solution so i decided to come here. Here is my code::
"app.js"
angular.module("sandwichApp",["cart", "ngRoute"])
.config(['$routeProvider', function($routeProvider){
$routeProvider
.
when("/",{
templateUrl: "app/views/sandwichList.html",
controller: "SandwichListController"
}).
when("/sandwichList",{
templateUrl: "app/views/sandwichList.html"
}).
when("/checkout",{
templateUrl: "app/views/cart.html"
}).
otherwise({
redirectTo: "/app/views/sandwichList.html"
});
}]);
// for this particular code i have tried the version where the config() doesn't contain array "[]" but only the function and it also doesn't work
"sandwichListController.js"
var main = angular.module("sandwichApp", ["clientAppServiceModule"]);
main.controller("SandwichListController", function($scope, ClientAppService, cart){
$scope.original = {
sandwiches : []
}
//.... more code here. THERE IS NO PROBLEM WITH THIS CONTROLLER SO THE CODE IS NOT IMPORTANT.
);
"index.html"
<!DOCTYPE html>
<html ng-app="sandwichApp">
<head>
<meta charset="UTF-8">
<title>title</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-route.js"></script>
<!--script src="https://cdn.jsdelivr.net/angularjs/1.5.5/angular-route.min.js"></script-->
<script src="app.js"></script>
<script src="app/services/clientAppService.js"></script>
<script src="app/controllers/sandwichListController.js"></script>
<script src="app/model/cart.js"></script>
</head>
<body ng-controller="SandwichListController">
<div><strong>Heading & Cart</strong></div>
<div ng-view></div>
</body>
</html>
"sandwichList.html"
<div>
<b>Your Cart: </b>
{{totalItems}} items / {{totPrice | currency}}
<span>checkout</span>
</div>
<div>
<input type="text" ng-model="sandwichName" ng-change="filterSandwich()"/>
</div>
<div>
<h1>Sandwiches </h1>
</div>
<div ng-repeat="sandwich in workingCopy.sandwiches">
<h3 ng-click="addItemToCart(sandwich)">
<strong>{{sandwich.Name}}</strong>
<span>{{sandwich.Price | currency}}</span>
</h3>
</div>
When i load the "index.html" page, i expect the "otherwise" section of the routeer to display the "sandwichList.html" in the <div ng-view></div> section but it doesn't work. If it can't find the file, it will complain but it doesn't complain meaning that the file is at the right location. Yet it does not work.
In the sandwichList page at least if the controllers will not work, it must be able to display the <h1>Sandwiches </h1> .
My chrome console doesn't display any errors so i don't know what is causing the problem
I think it might be because you are accidentally declaring your app twice. When registering a new module in angular you provide it a second parameter which is an array of dependencies. You are doing that where you specify your routes. However, when you go to create your controller, you're code is this:
var main = angular.module("sandwichApp", ["clientAppServiceModule"]);
Angular sees the dependencies and assumes it is to create a new app. When it realizes there is already one with the same name, it overwrites it and you lose all the route stuff you setup. Try passing your "clientAppServiceModule" to the initial app definition, then just creating your controller by doing this:
angular.module("sandwichApp").controller("SandwichListController", function($scope, ClientAppService, cart){
$scope.original = {
sandwiches : []
}
//.... more code here. THERE IS NO PROBLEM WITH THIS CONTROLLER SO THE CODE IS NOT IMPORTANT.
);
Let me know if you have any questions, or if that doesn't solve it.

Angular 2 and Laravel 5.2 - Display Different Blade Templates

I've just managed to get Laravel and AngularJS 2 setup together.. albeit a very simple setup ie I have a main welcome.blade.php file that shows as the index page, however, I would like to make some kind of navigation where you can switch between pages and angular will pull the info in from various blade templates and this is where I am stuck, I understand how to generate the nav in angular etc but I am not sure what to add to the #component({template:xxxxxxxxxx}) field in order for it to pull in blade templates.. does anyone have any examples of how to render these external templates in the angular components ? below is what i have so far and it injects My First Angular 2 App into the default laravel welcome page.
app.components.ts
///<reference path="../../../public/js/angular2/core.d.ts"/>
import {Component} from 'angular2/core';
#Component({
selector: 'my-app',
template: '<h1>My First Angular 2 App</h1>'
})
export class AppComponent { }
boot.ts
///<reference path="../../../public/js/angular2/typings/browser.d.ts"/>
/* the above file fixes an issue with promises etc - was getting loads of errors then found this http://stackoverflow.com/questions/35382157/typescript-build-getting-errors-from-node-modules-folder*/
import {bootstrap} from 'angular2/platform/browser'
import {AppComponent} from './app.component'
bootstrap(AppComponent);
welcome.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel</title>
<script src="{{ url('/') }}/js/es6-shim/es6-shim.min.js"></script>
<script src="{{ url('/') }}/js/systemjs/dist/system-polyfills.js"></script>
<script src="{{ url('/') }}/js/angular2/es6/dev/src/testing/shims_for_IE.js"></script>
<script src="{{ url('/') }}/js/angular2/bundles/angular2-polyfills.js"></script>
<script src="{{ url('/') }}/js/systemjs/dist/system.src.js"></script>
<script src="{{ url('/') }}/js/rxjs/bundles/Rx.js"></script>
<script src="{{ url('/') }}/js/angular2/bundles/angular2.dev.js"></script>
<script type="text/javascript">
System.config({
"baseURL": '/js',
"defaultJSExtensions": true,
"packages": {
typescript: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('typescript/boot').then(null, console.error.bind(console));
</script>
</head>
<body>
<div class="container">
<div class="content">
<div class="title">Laravel 5</div>
<my-app>Loading...</my-app>
</div>
</div>
</body>
</html>
Maybe I am very mistaken, but from what I understand Angular cannot render blade templates? They are first rendered by Laravel before being sent as regular HTML with whatever was filled in on the template. Then Angular is initialized and works with the HTML document. I typically like to let Angular handle all my routing and make it a SPA by just redirecting any undefined routes in routes.php to a single index page where Angular's router will render different views. Sadly, I have not made the transition yet to Angular 2 so I'm not sure how the router is setup. But this is just a route file I use that has a "catch-all" so to speak that redirects to the index page.
Route::group(["prefix" => "api"], function() {
Route::resource("users", "UsersController");
Route::group(["prefix" => "users"], function() {
Route::get("{id}/places", "UsersController#getPlaces");
Route::get("{id}/searches", "UsersController#getSearches");
});
Route::resource("places", "PlacesController");
Route::resource("searches", "SearchesController");
Route::group(["prefix" => "auth"], function() {
Route::get("/", "AuthController#GetAuth");
Route::get("logout", 'Auth\AuthController#logout');
});
});
Route::get('/', 'RedirectController#toAngular');
// Authentication Routes...
Route::get('login', 'RedirectController#toAngular'); // Override, let Angular handle login form
Route::post('login', 'Auth\AuthController#login');
Route::get('logout', 'Auth\AuthController#logout');
// Registration Routes...
Route::get('register', 'RedirectController#toAngular');
Route::post('register', 'Auth\AuthController#register');
// Password Reset Routes...
Route::get('password/reset/{token?}', 'Auth\PasswordController#showResetForm');
Route::post('password/email', 'Auth\PasswordController#sendResetLinkEmail');
Route::post('password/reset', 'Auth\PasswordController#reset');

Angularjs: Error: [ng:areq] Argument 'HomeController' is not a function, got undefined

This is my demo using angularjs, for creating a service file, and adding service to a controller.
I have two problems with my demo:
One is when I put <script src="HomeController.js"> before <script src="MyService.js"> I get this error,
Error: [ng:areq] Argument 'HomeController' is not a function, got undefined
The other is when I put <script src="MyService.js"> before <script src="HomeController.js"> I get the following error,
Error: [$injector:unpr] Unknown provider: MyServiceProvider <- MyService
My source:
File Index.html:
<!DOCTYPE html>
<html >
<head lang="en">…</head>
<body ng-app="myApp">
…
<div ng-controller="HomeController">
<div ng-repeat="item in hello">{{item.id + item.name}}</div>
</div>
<script src="Scripts/angular.js"></script>
<script src="Scripts/angular-route.js"></script>
<!-- App libs -->
<script src="app/app.js"></script>
<script src="app/services/MyService.js"></script>
<script src="app/controllers/HomeController.js"></script>
</body>
</html>
File HomeController.js:
(function(angular){
'use strict';
var myApp = angular.module('myApp',[]);
myApp.controller('HomeController',function($scope,MyService){
$scope.hello=[];
$scope.hello = MyService.getHello();
});
})(window.angular);
File MyService.js:
(function(angular){
'use strict';
var myApp = angular.module('myApp',[]);
myApp.service('MyService', function () {
var hello =[ {id:1,name:'cuong'},
{id:2,name:'nguyen'}];
this.getHello = function(){
return hello;
};
});
})(window.angular);
This creates a new module/app:
var myApp = angular.module('myApp',[]);
While this accesses an already created module (notice the omission of the second argument):
var myApp = angular.module('myApp');
Since you use the first approach on both scripts you are basically overriding the module you previously created.
On the second script being loaded, use var myApp = angular.module('myApp');.
I experienced this error once. My problem was that I wasn't adding the FILE_NAME_WHERE_IS_MY_FUNCTION.js
so my file.html never found where my function was
Once I add the "file.js" I resolved the problem
<html ng-app='myApp'>
<body ng-controller='TextController'>
....
....
....
<script src="../file.js"></script>
</body>
</html>
Also ensure that your controllers are defined within script tags toward the bottom of your index.html just before the closing tag for body.
<!-- build:js({.tmp,app}) scripts/scripts.js -->
<script src="scripts/app.js"></script>
<script src="scripts/controllers/main.js"></script>
<script src="scripts/controllers/Administration.js"></script>
<script src="scripts/controllers/Leaderboard.js"></script>
<script src="scripts/controllers/Login.js"></script>
<script src="scripts/controllers/registration.js"></script>
provided everything is spelled "correctly" (the same) on your specific.html, specific.js and app.js pages this should resolve your issue.
Happened to me few times whenever I miss "," between list of injections and function
app.controller('commonCtrl', ['$scope', '$filter',function($scope,$filter) {
}]);
I also experienced this error but in my case it was because of controller naming convention. I declared controller: "QuestionController" in .state but in controller definition I declared it like
yiiExamApp.controller('questionController' ...
but it should be
yiiExamApp.controller('QuestionController' ...
hope that helps to people facing this error because of this stupid mistake I wasted 4hour in identifying it.
I also encountered this same error and the fix for me was to include my child module in the main module array.
var myApp = angular.module('myApp', ['ngRoute', 'childModuleName']);
If ALL ELSE fails and your running locally on the MEAN stack like me with gulp...just stop and serve again! I was pulling my hear out meticulously checking everything from all of your posts to no avail till I simply re-ran gulp serve.
I got the same error. I defined java script like this
<script src="controllers/home.js" />
then I changed to the this
<script src="controllers/home.js"></script>
After this my problem is solved.
I had similar issue. The fix was ensure that your ctrollers are not only defined within script tags toward the bottom of your index.html just before the closing tag for body but ALSO validating that they are in order of how your folder is structured.
<script src="scripts/app.js"></script>
<script src="scripts/controllers/main.js"></script>
<script src="scripts/controllers/Administration.js"></script>
<script src="scripts/controllers/Leaderboard.js"></script>
<script src="scripts/controllers/Login.js"></script>
<script src="scripts/controllers/registration.js"></script>
I also encountered this problem in my project. It eventually worked after I inserted the my-controller.js into my karma.conf.js file, with the <script> tag.
Hope this will help. There are quite many reasons that can lead to this problem.
I also got this error.
I had to add my new controller to routing information.
\src\js\app.js
angular.module('Lillan', [
'ngRoute',
'mobile-angular-ui',
'Lillan.controllers.Main'
])
I added my controller to make it look like
angular.module('Lillan', [
'ngRoute',
'mobile-angular-ui',
'Lillan.controllers.Main',
'Lillan.controllers.Growth'
])
Cheers!
Obviously that previous posts are useful, but any of above are not helpful in my case. The reason was in wrong sequence of loading scripts. For example, in my case, controller editCtrl.js depends on (uses) ui-bootstrap-tpls.js, so it should be loaded first.
This caused an error:
<script src="scripts/app/station/editCtrl.js"></script>
<script src="scripts/angular-ui/ui-bootstrap-tpls.js"></script>
This is right, works:
<script src="scripts/angular-ui/ui-bootstrap-tpls.js"></script>
<script src="scripts/app/station/editCtrl.js"></script>
So, to fix the error you need first declare all scripts without dependencies, and then scripts that depends on previously declared.
Try this
<title>My First Angular App</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<h3>Adding Simple Controller<h3>
<div ng-controller="SimpleController">
Name:
<br/>
<input type = "text" data-ng-model = "name"/> {{name}}
<br/>
<ul>
<li data-ng-repeat = "cust in customers | filter:name | orderBy:'city'">
{{cust.name}} - {{cust.city}}
</li>
</ul>
</div>
<script>
var angularApp = angular.module('angularApp',[]);
angularApp.controller('SimpleController', [ '$scope', SimpleController]);
function SimpleController($scope)
{
$scope.customers = [
{name:'Nikhil Mahirrao', city:'Pune'},
{name:'Kapil Mahire', city:'Pune'},
{name:'Narendra Mahirrao', city:'Phophare'},
{name:'Mithun More', city:'Shahada'}
];
}
</script>
</body>
In my case, I was missing the name of the Angular application in the html file. For example, I had included this file to be start of my application code. I had assumed it was being ran, but it wasn't.
app.module.js
(function () {
'use strict';
angular
.module('app', [
// Other dependencies here...
])
;
})();
However, when I declared the app in the html I had this:
index.html
<html lang="en" ng-app>
But to reference the Angular application by the name I used, I had to use:
index.html (Fixed)
<html lang="en" ng-app="app">
I was getting the error because i had added the controller script before the script where i had defined the corresponding module in the app.
First add the script
<script src = "(path of module.js file)"></script>
Then only add
<script src = "(path of controller.js file)"></script>
In the main file.
Error: ng:areq Bad Argument has gotten me a couple times because I close the square bracket too soon. In the BAD example below it is closed incorrectly after '$state' when it should actually go before the final parenthese.
BAD:
sampleApp.controller('sampleApp', ['$scope', '$state'], function($scope, $state){
});
GOOD:
sampleApp.controller('sampleApp', ['$scope', '$state', function($scope, $state){
}]);
Yes. As many have previously pointed out,
I have added the src path to all the controller files in the index.html.
<script src="controllers/home.js"></script>
<script src="controllers/detail.js"></script>
<script src="controllers/login.js"></script>
<script src="controllers/navbar.js"></script>
<script src="controllers/signup.js"></script>
This fixed that error.
I had the same problem, but I forgot to include the file into grunt/gulp minimization process.
grunt.initConfig({
uglify: {
my_target: {
files: {
'dest/output.min.js': ['src/input1.js', 'src/missing_controller.js']
}
}
}
});
Hope that helps.
In my situation this error appeared when I didn't declare function within an array argument.
The one with error:
taskAppControllers.controller('MainMenuCtrl', []);
The fixed one:
taskAppControllers.controller('MainMenuCtrl', [function(){
}]);
Also check for spelling mistakes.
var MyApp = angular.module('AppName',[]);
MyApp.controller('WRONG_SPELLING_MyCtrl', ['$scope', MyControllerCtrl])
function MyControllerCtrl($scope) {
var vm = $scope;
vm.Apple = 'Android';
}
<div ng-controller="ACTUAL_SPELLING_MyCtrl">
{{Apple}}
</div>
Check if your HTML page includes:
angular.min script
app.js
controller JavaScript page
The order the files are included is important. It was my solution to this problem.
Hope this helps.
sampleApp.controller('sampleApp', ['$scope', '$state', function($scope, $state){
Same thing for me, comma ',' before function helped me in fixing the issue -- Error: ng:areq Bad Argument
My controller file was cached as empty. Clearing the cache fixed it for me.
I accidentally moved my HomeController.js out of the directly, where it was expected.
Putting it again on original location.
After that my website started to load pages automatically every second, I was even unable to look at the error. So i cleared the browser cache. It solved the problem
For me the solution was to add a semicolon after one of the functions declared in my HomeController.js
//Corrected code is :
app.controller('HomeController', function($scope, $http, $log) {
$scope.demo1 = function(){
console.log("In demo");
} //Here i forgot to add the semicolon
$scope.demo2 = function(){
console.log("In demo");
};
});

Single Page Application View Location

I think I have a gross misunderstanding as to how routing in AngularJS works, and SPA's altogether.
I had thought with my simple routing :
$routeProvider
.when('/home', {
templateUrl: 'app/views/home.html',
controller: 'homeController'
})
.when('/login', {
templateUrl: 'app/views/login.html',
controller: 'loginController',
})
I had thought that when I went to /login, angular made an ajax call to grab the html page it needed. However, I don't see any calls going through fiddler, and that doesn't really make sense.
But I can't seem to locate where the pages are in my Chrome Developer Tools, nor find the correct word combination to get a suitable answer through google. Can someone clear this up for me?
if it helps, here's the body of my layout page:
<body ng-cloak>
<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
...nav stuff
</nav>
<br/><br/>
<div class="container body-content" ng-view></div>
<!-- 3rd party scripts -->
<script src="Scripts/angular.js"></script>
<script src="Scripts/angular-local-storage.min.js"></script>
<script src="Scripts/jquery-2.1.1.min.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
<script src="Scripts/angular-route.min.js"></script>
<!-- app main -->
<script src="app/app.js"></script>
<!-- controllers -->
<script src="app/controllers/homeControllers.js"></script>
<script src="app/controllers/loginController.js"></script>
<!-- services -->
<script src="app/services/modelErrorService.js"></script>
<script src="app/services/authInterceptorService.js"></script>
<script src="app/services/authService.js"></script>
</body>
EDIT
Sorry I may have been unclear. The code works fine. My question is, when angular routes you to a new page, where is it loading that html template from? Is it all delivered to the client at the get-go, or is it calling back to the server? If it is on the client, where is it stored?
If templateUrl is specified, Angular will look into the $templateCache for the template and load it from there if found. If not found, it will try to fetch it from the server, store it in $templateCache for future access and load it into view.
Templates can be put into Angular's $templateCache
when fetched from the server for the first time
by placing them in the HTML, in a <script type="text/ng-template"></script> element
by programmatically putting them into the $templateCahce (for whatever reason: performance, offline access etc)
Your code looks just fine.
Have you injected the ngRoute module into your application like so:
angular.module('your-app-name', ['ngRoute']);

Ember - how do I do simplest possible routes?

Ok, being minimalist, I have an index.html that has
<html>
<body>
hello world
<script type="text/x-handlebars" data-template-name="lists">
<h1>in route lists</h1>
</script>
<script src="http://builds.emberjs.com/beta/ember.js"></script>
<script src="app.js"></script>
</body>
</html>
and an app.js with
var App = window.App = Ember.Application.create({
LOG_TRANSITIONS: true
});
App.Router.map(function() {
this.resource('lists');
});
Shouldn't that be enough to get me a page with 'in route lists' when I navigate to AppURL/lists?
This is enough to get you a page with 'in route lists'. The page will be at APP_URL/#/lists though as by default ember uses the browsers hash for routing. If you wish to use hashless urls you need to tell your router to use the HTML5 history API:
App.Router.reopen({
location: 'history'
});
You can read more about this here:
http://emberjs.com/guides/routing/specifying-the-location-api/
and find a JSBin to play about here:
http://emberjs.jsbin.com/seweqedi/2/

Categories

Resources