Issues With Angular ngRoute - javascript

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.

Related

Angular Material and md-nav-bar routing

I'm digging into Angular and have decided to use the Angular Material library to assist in my first application. So far I have some very basic code I copied from https://material.angularjs.org/1.1.0/demo/navBar which I have modified to fit my own needs. I'm having some trouble wrapping my head around routing and the md-nav-items.
<html>
<head>
<title>PRT - CIT</title>
<meta name="viewport" content="width=device-width, initial-scale=1" </meta>
<!-- Angular Material style sheet -->
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.css">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic"> </head>
<body ng-app="MyApp" id="bootstrap-overrides">
<div ng-controller="AppCtrl" ng-cloak="" class="navBardemoBasicUsage main">
<md-content class="md-padding">
<md-nav-bar md-selected-nav-item="currentNavItem" nav-bar-aria-label="navigation links">
<md-nav-item md-nav-click="goto('queue')" name="queue">Queue</md-nav-item>
<md-nav-item md-nav-click="goto('detail')" name="detail">Detail</md-nav-item>
<md-nav-item md-nav-click="goto('request')" name="request">Request</md-nav-item>
<!-- these require actual routing with ui-router or ng-route, so they won't work in the demo
<md-nav-item md-nav-sref="app.page4" name="page4">Page Four</md-nav-item>
<md-nav-item md-nav-href="#page5" name="page5">Page Five</md-nav-item>
--></md-nav-bar>
<div class="ext-content"> External content for `<span>{{currentNavItem}}</span>` </div>
</md-content>
</div>
<script src="node_modules/angular/angular.js"></script>
<script src="node_modules/angular-resource/angular-resource.js"></script>
<script src="node_modules/angular-animate/angular-animate.js"></script>
<script src="node_modules/angular-route/angular-route.js"></script>
<script src="node_modules/angular-aria/angular-aria.js"></script>
<script src="node_modules/angular-messages/angular-messages.js"></script>
<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-114/svg-assets-cache.js"></script>
<script src="node_modules/angular-material/angular-material.js"></script>
<script src="js/site.js"></script>
<link rel="stylesheet" href="/css/site.css">
</body>
</html>
Here's my JS:
(function () {
'use strict';
var MyApp = angular.module('MyApp', ['ngMaterial', 'ngMessages', 'material.svgAssetsCache', 'ngRoute']).controller('AppCtrl', AppCtrl);
function AppCtrl($scope) {
$scope.currentNavItem = 'queue';
}
MyApp.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/index.html'
, controller: 'AppCtrl'
}).when('/queue', {
templateUrl: '/partials/queue.html'
, controller: 'AppCtrl'
}).when('/detail', {
templateUrl: '/partials/detail.html'
, controller: 'AppCtrl'
}).when('/request', {
templateUrl: '/partials/request.html'
, controller: 'AppCtrl'
});
});
})();
I'm kind of lost as to how I should route the tabs. From what I've read, md-nav-bar has some routing built in, but I've found examples utilizing ngRoute as well ui-router.
I'm also confused as to actually populate my partial views in the
<div class="ext-content"> External content for `<span>{{currentNavItem}}</span>` </div>
I tried using md-nav-href instead of md-nav-click but it just ended up redirecting me to the pages, not populating the content below my tabs/nav-bar; I rolled back the JS I had written and that part of the HTML. I've read the other questions posted in this area that I could find but none addressed rendering different partials based on nav-bar item. Any suggestions? I was thinking I could monitor currentNavItem and have the right partial render based on the value of it, but again, I'm not sure how to actually do the rendering.
Here is a Plnker that doesn't render correctly in the preview for some reason, but the code is the same as what I have locally.
Here is an image of what it looks like running locally.
Thanks in advance!
Final Edit:
S/O to #Searching for helping me get it working below. I've updated the plnker link to reflect the changes. Note it gets a little laggy due to the base append script.
ngRoute: When $route service you will need ng-view container. This will be used to load all you routed pages.
You do not have a goto() so just use simple md-nav-href tags to navigate around. The currentNavItem is set by md-selected-nav-item which is not what you need. Let's route with your setup
index.html : update your links to look like this. Use md-nav-href
<md-nav-item md-nav-href="queue" name="queue">Queue</md-nav-item>
index.html : when using html5Mode you will need base tag. Instead of manually specifying it just use the script below. Make sure you load angular.js before this script.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.js"></script>
<script type="text/javascript">
angular.element(document.getElementsByTagName('head')).append(angular.element('<base href="' + window.location.pathname + '" />'));
</script>
script : enable html5molde, why.. too many resources out there. I encourage you to lookup :)
MyApp.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true)
$routeProvider.when('/', {
templateUrl : 'index.html',
controller : 'AppCtrl'
}).when('/queue', {
templateUrl : 'queue_partial.html',//actual location will vary according to your local folder structure
controller : 'AppCtrl'
}).when('/detail', {
templateUrl : 'detail_partial.html',
controller : 'AppCtrl'
}).when('/request', {
templateUrl : 'request_partial.html',
controller : 'AppCtrl'
});
});

Angularjs: How To Call Controller Function After Routing

I'm learning angularjs and there is one aspect of it that I'm struggling to understand.
My desired/expected behavior of the code below is:
User clicks the Paris link (anchor tag)
The routeProvider intercepts the request, loads the paris.html page into the ng-view.
The 'getCity' function in the controller gets the data and sets the scope variables, which are displayed in the london.html expressions.
However, I can't figure out how to config angularjs to use the 'getCity' function when the html page is loaded into the ng-view. The closest I can get is calling the 'getCity' function from within the CityController itself, bit this seems to have the undesired effect of calling the function when the whole app (index.html) is loaded instead of only when the link is clicked. The controller will have a number of different functions.
I also know you can use ng-click to call a controller's function, but I'm unsure how this would work with loading a html page into an ng-view through the route provider.
Any help would be appreciated. Please see code below from a small app built for learning purposes:
index.html
<!DOCTYPE html>
<html ng-app="mainApp">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-route.js"></script>
</head>
<body>
<ol>
<li>Paris</li>
</ol>
<div class="content-wrapper" ng-controller="CityController">
<div ng-view></div>
</div>
<script src="resources/js/app.js"></script>
<script src="resources/js/CityController.js"></script>
</body>
</html>
app.js
var app = angular.module("mainApp", [ 'ngRoute' ]);
app.config([ '$routeProvider', function($routeProvider) {
$routeProvider.
when('/cities/paris', {
templateUrl : 'resources/paris.html',
controller : 'CityController'
}).
otherwise({
redirectTo : ''
});
} ]);
CityController.js
app.controller('CityController', function($scope, $http) {
$scope.getCity = function() {
$http.get('city')
.success(function(response) {
$scope.name = response.name;
$scope.country = response.country;
}).error(function() {
//Output error to console
});
};
//$scope.getCity();
});
I don't want to call getCity here because it means the http get request to
the 'city' endpoint is called when index.html is loaded
paris.html
This is Paris.
<br><br><br>
Name: {{name}}<br>
Country: {{country}}
<br><br><br>
I think what you are looking for is the router resolve option.
A resolve contains one or more promises that must resolve successfully before the route will change. This means you can wait for data to become available before showing a view, and simplify the initialization of the model inside a controller because the initial data is given to the controller instead of the controller needing to go out and fetch the data.
Check the explanation and usage here
You can call getCity() from paris.html using ,ng-init=getCity() ,ng-init will call your function as soon as paris.html is loaded into your ng-view .
For Eg.
This is Paris.
<br><br><br>
<div ng-init=getCity() >
Name: {{name}}<br>
Country: {{country}}
</div>
<br><br><br>

Angular ngRoute can't load template: Error [$compile:tpload]

I tried some simple Angular Routing, but I cant specify what's the error. Chrome just tells me that Angular can't compile the Template.
In the following Link you can see my directory structure.
directory-structure
-- angular.js
var testApp = angular.module('testApp', ['ngRoute']);
testApp.config(function($routeProvider){
$routeProvider.when('/list', {
templateUrl: 'pages/list.html',
controller: 'mainController'
}).when('/insert', {
templateUrl: 'pages/new.html',
controller: 'newController'
});
});
testApp.controller('mainController', function($scope){
$scope.message = 'main';
});
testApp.controller('newController', function($scope){
$scope.message = 'new';
});
--index.html
<!DOCTYPE html>
<html lang="en" ng-app="testApp">
<head>
<meta charset="UTF-8">
<title>Barfly</title>
<script src="/angular/angular.min.js"></script>
<script src="/angular-route/angular-route.min.js"></script>
<script src="/js/angularApp.js"></script>
</head>
<body ng-controller="mainController">
list
new
<div id="main">
<div ng-view></div>
</div>
</body>
</html>
This is my error,
Browser Error
Thank you in advance!
EDIT. Sorry, I didn't see your directory structure. Are you sure pages directory is accessible to the public? Should the pages directory be moved into public directory?
Old answer:
The error is saying the templateUrl /pages/list.html does not exists. You should either save a template file into /pages/list.html file or add an inline template in the html body like this:
<script type="text/ng-template" id="/pages/list.html">
my template here
</script>
I encountered a sort of similar problem: templateUrl files could be not loaded (all resources didn't). In my case it happened when app was loaded on a browser on a mobile device. It was caused by Content Security Policy restrictions (How does Content Security Policy work?)
I got the CSP to permit all resources except for the templates referenced by templateUrl.
I also tried loading the templates through the script directive (https://docs.angularjs.org/api/ng/directive/script), but to no avail.
Eventually I decided to embed the templates in the route itself, like this:
testApp.config(function($routeProvider){
$routeProvider.when('/list', {
template: '<li ng-repeat="etcetera"></li>',
controller: 'mainController'
});
});
<a data-target="#list">list</a>
<a data-target="#insert">new</a>

How does one map many routes in AngularJS?

An AngularJS site with a Spring Boot backend has numerous public url patterns in addition to a secure section. All the public url patterns fall in the model mydomain.com/public1, mydomain.com/public2, mydomain.com/public3, and so on, while all the secure content will be inside the mydomain.com/secure url pattern like mydomain.com/secure/one_of_many_urls. The problem is that the sample app I am starting with has separate modules for every route. This would become hard to maintain with n routes.
How can I set the code up so that all the public1, public2, public3, public_n routes share a single controller?
Here is the current directory structure. I would like for the public1 directory to turn into public and be able to map as many specific url patterns as I want to put into it:
In addition, my public1.js is currently empty as follows:
angular.module('public1', []).controller('public1', function($scope, $http) {
});
The link to the public1 route is handled in a navigation bar in index.html as follows:
<!doctype html>
<html>
<head>
<title>Hello Angular</title>
<!-- To produce natural routes (without the #), you need an extra <base/> element in the header of the HTML in index.html, and you need to change the links in the menu bar to remove the fragments ("#"). There are also changes in a spring controller and in the main js module. -->
<base href="/" />
<link href="css/angular-bootstrap.css" rel="stylesheet">
<style type="text/css">
[ng\:cloak], [ng-cloak], .ng-cloak {
display: none !important;
}
</style>
</head>
<body ng-app="hello" ng-cloak class="ng-cloak">
<div ng-controller="navigation" class="container">
<ul class="nav nav-pills" role="tablist">
<li ng-class="{active:tab('home')}">home</li>
<li ng-class="{active:tab('message')}">message</li>
<li ng-class="{active:tab('public1')}">public1</li>
<li>login</li>
<li ng-show="authenticated()">logout</li>
</ul>
</div>
<div ng-view class="container"></div>
<script src="js/angular-bootstrap.js" type="text/javascript"></script>
<script src="js/auth/auth.js" type="text/javascript"></script>
<script src="js/home/home.js" type="text/javascript"></script>
<script src="js/message/message.js" type="text/javascript"></script>
<script src="js/public1/public1.js" type="text/javascript"></script>
<script src="js/navigation/navigation.js" type="text/javascript"></script>
<script src="js/hello.js" type="text/javascript"></script>
</body>
</html>
And public1.html is:
<h1>Public 1</h1>
<div>
<p>This will be a public url pattern.</p>
</div>
How do I change the code below so that a scaling n number of public routes can efficiently share the same controller? Each public_n route will have their own images, but would share js logic, if they have any js logic.
I found the following, but where would one put it in the code above, and how would a person link everything to it without resorting to leaving it in hello.js?
.when('/public1', {
templateUrl: 'js/public/public1.html'
}
.when('/public2', {
templateUrl: 'js/public/public2.html'
}
.when('/public3', {
templateUrl: 'js/public/public3.html'
})
How do I change the code below so that a scaling n number of public
routes can efficiently share the same controller?
You can Associate one Controller to Many Routes (Views) just assigning it to more routes in your $routeProvider as follows:
myApp.config(function ($routeProvider) {
$routeProvider
.when('/public1', {
templateUrl: 'js/public/public1.html',
controller: 'myController'
})
.when('/public2', {
templateUrl: 'js/public/public2.html',
controller: 'myController'
})
.when('/public3', {
templateUrl: 'js/public/public3.html',
controller: 'myController'
})
.otherwise({
redirectTo: '/'
});
})
You can also Set a Controller Alias as follows:
.when('/public1', {
templateUrl: 'js/public/public1.html',
controller: 'myController',
controllerAs: 'myCtrl'
})
I found the following, but where would one put it in the code above,
and how would a person link everything to it without resorting to
leaving it in hello.js?
If I got your question, you just need to put the $routeProvider in a separated routeProvider.js file and include it in your index.html. Same thing for your controller/controllers.
I suggest you to take a look at:
AngularJS Controllers Documentation
AngularJS $routeProvider Documentation
Follow the first lesson of - CodeSchool - Staying Sharp with AngularJS
EggHead.io AngularJS Screencasts
And also take a look at those Q/A on StackOverflow:
Using one controller for many coherent views across multiple HTTP requests
Views sharing same controller, model data resets when changing view
Controlling multiple views in one controller in AngularJS
Can I use one controller updating two views in AngularJS?
I hope I've been helpful.

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");
};
});

Categories

Resources