AngularJs controller in two separate files - angularjs

In my Javascript file I have the following code:
var app = angular.module('allApps',['ngRoute', 'ui.bootstrap']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
template: ''
})
.when('/user', {
templateUrl: 'pages/user.html'
})
.when('/gallery', {
templateUrl: 'pages/gallery.html'
})
.when('/contacts', {
templateUrl: 'pages/contacts'
})
.otherwise({
redirectTo: '/'
});
}]);
Now, through ng-route I have another page called user.html that is simple this:
<div ng-controller = "Ctrl2">
{{user.name}}
</div>
<script type="text/javascript">
angular.module('allApps').controller('Ctrl2',function($scope){
$scope.user={name:"Jim", lastname:"Smith"};
});
</script>
In my HTML file I have the following code:
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-route.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-animate.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-1.2.1.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src ="js/script.js"></script>
<link href="css/style.css" rel="stylesheet">
But it doesn't work. Error:
Error: [ng:areq] http://errors.angularjs.org/1.4.8/ng/areq?p0=Ctrl2&p1=not%20a%20function%2C%20got%20undefined
G/<#http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:6:416
qb#http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:22:131
Qa#http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:22:218
Xe/this.$get</<#http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:80:210
w#http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:60:177
D#http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:61:30
g#http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:55:105
K/<#http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:54:249
ngViewFillContentFactory/<.link#https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-route.js:986:7
ea#http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:73:293
D#http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:62:190
g#http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:55:105
K/<#http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:54:249
R/<#http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:56:79
k#http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:60:377
update#https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-route.js:936:25
lf/this.$get</r.prototype.$broadcast#http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:136:157
commitRoute/<#https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-route.js:619:15
f/<#http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:119:129
lf/this.$get</r.prototype.$eval#http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:133:309
lf/this.$get</r.prototype.$digest#http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:130:404
lf/this.$get</r.prototype.$apply#http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:134:76
g#http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:87:442
T#http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:92:50
Uf/</w.onload#http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js:93:78
<div class="ng-scope" ng-view="">
What am I doing wrong?
Thanks in advance.

You can't add controllers after angular is already bootstrapped, unless you use some kind of fancy lazy-loading. Therefore, adding a controller from a script block on a view is just not going to work.

You can have multiple controllers in differenct script files. But the script file should copile first before you start rendering the view.
Try binding your controller to the template view in the routes config
var app = angular.module('allApps',['ngRoute', 'ui.bootstrap']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
template: '',
controller: 'Ctrl1'
})
.when('/user', {
templateUrl: 'pages/user.html',
controller: 'Ctrl2'
})
.when('/gallery', {
templateUrl: 'pages/gallery.html',
controller: 'Ctrl3'
})

you are not closing your first function well. It should
var app = angular.module('allApps',['ngRoute', 'ui.bootstrap']);
app.controller('Ctrl1',[ '$scope', function ($scope){
...
}]);

Related

AngularJS: Controller inside ng-view

I have problem with controller load when I triggered ng-route.
This is my main page:
<!DOCTYPE html>
<html>
<head ng-app="testapp">
<script type="text/javascript" src="angular.js"></script>
<script type="text/javascript" src="angular-route.js"></script>
<script type="text/javascript" src="app.js"></script>
<title>XX</title>
</head>
<body>
<nav ng-controller="defaultnav"></nav>
<div ng-view></div>
</body>
</html>
and this is my app.js file:
var app = angular.module('testapp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.
when("/", {
templateUrl: "index.html"
})
.when("/page1", {
templateUrl: "page1.html"
})
})
inside the page1.html I inisiate controller like this:
<div ng-controller="page1">
</div>
<script type="text/javascript">
app.controller('page1', function ($scope) {
// code...
})
</script>
I don't know best practice to handle this. When I code this I got error with [Error, ctrlreg] it says that I have problem about registering controller.
Please give me advice to solve this.
Thanks in advance.
In JS, the app name in line var app = angular.module('enterprise', ['ngRoute']); is enterprise
In HTML, <head ng-app="testapp">, the app name is testapp. Change to <head ng-app="enterprise">
Its best practice to load the java script seperately. so remove js code from html and keep it in seperate file and load it
Click here for working demo in plnkr.
You can use AngularJS ngRoute:
// create the module and name it scotchApp
var scotchApp = angular.module('scotchApp', ['ngRoute']);
// configure our routes
scotchApp.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/home', {
templateUrl: 'pages/home.html',
controller: 'mainController'
})
// route for the about page
.when('/about', {
templateUrl: 'pages/about.html',
controller: 'aboutController'
})
// route for the contact page
.when('/contact', {
templateUrl: 'pages/contact.html',
controller: 'contactController'
})
//otherwise redirect to home
.otherwise({
redirectTo: "/home"
});
});
// create the controller and inject Angular's $scope
scotchApp.controller('mainController', function($scope) {
// create a message to display in our view
$scope.message = 'Everyone come and see how good I look!!!!';
});
scotchApp.controller('aboutController', function($scope) {
$scope.message = 'Look! I am an about page.';
});
scotchApp.controller('contactController', function($scope) {
$scope.message = 'Contact us!.';
});

AngularJS routing with templateUrl

I have a problem with the AngularJS routing: I don't get any feedback of the page. No errors or view-switches.
I checked my implementation of the module, but it's declared in the right way. Then I searched for typos such as templateURL, but I didn't find any. I also tried to use ng-href instead of href in the list, but then the links weren't clickable anymore.
Here is my plunker.
And my code:
Created my navigation:
<body ng-app="Productportfolio">
<ul>
<li>
Home
</li>
<li>
<a href='#/privat'>Log in</a>
</li>
</ul>
<ng-view></ng-view>
<!--own js -->
<script src="app.js"></script>
<!--Controller -->
<script src="ProductCtrl.js"></script>
<!--Services -->
<!--Direktives-->
</body>
Made the templates:
//home.html
<div>
<h1> Home </h1>
</div>
//private.html
<div>
<h1> Private</h1>
</div>
Declared a Angular module:
angular.module('Productportfolio', ['ngRoute'])
Added the $routeProvider to my config:
angular.module('Productportfolio', ['ngRoute', 'ProductService', 'ProductCtrl'])
.config(['$routeProvider, $locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'ProductCtrl'
})
.when('/private', {
templateUrl: 'private.html',
controller: 'ProductCtrl'
})
.otherwise({
redirectTo: '/home',
controller: 'ProductCtrl'
});
$locationProvider.hashPrefix('!');
}]);
In your Plunker, there were some issues related to imports. To make it easy, I simply removed both jQuery and Bootstrap. I also put all your modules in a single app.js file.
There were some errors in your html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<!--AngularJS-->
<script data-require="angularjs#1.5.8" data-semver="1.5.8" src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"></script>
<script data-require="angular-route#1.5.8" data-semver="1.5.8" src="https://code.angularjs.org/1.5.8/angular-route.js"></script>
</head>
<body ng-app="Productportfolio">
<ul>
<li>
<a ng-href="#home">Home</a>
</li>
<li>
<a ng-href="#private">Private</a>
</li>
</ul>
<ng-view></ng-view>
<!--own js -->
<script src="app.js"></script>
</body>
</html>
Import Angular BEFORE ngRoute or any other module
Use ng-href='#routeName' or, otherwise
And in your js:
var myApp = angular.module('Productportfolio', ['ngRoute']);
myApp.controller('ProductCtrl', ['$scope',function ($scope) {
var vm = this;
}]);
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'ProductCtrl'
})
.when('/private', {
templateUrl: 'private.html',
controller: 'ProductCtrl'
})
.otherwise({
redirectTo: '/home',
controller: 'ProductCtrl'
});
}]);
You need to inject only external modules in your app module, not all controller, services etc
Notice that, to make it easy, I removed also your Service since you did not share it and it was useful.
Last but not least, if you want to use $locationProvider.hashPrefix('!'); to use hashbangs, you need to add <base href="/" /> at the end of your head.
For some reason, plunker does not allow me to do that, but I'm sure you'll get it to work on your version.
Here You can find the working plunker reproducing your application.
Hope I've been helpful.
The remaining and not visible problem is here :
angular.module('Productportfolio', ['ngRoute', 'ProductService', 'ProductCtrl'])
.config(['$routeProvider, $locationProvider',
config() function of module object takes as parameter, a array of strings and not a string with "," as separator char inside it.
See example and doc here :
https://docs.angularjs.org/guide/providers#provider-recipe
So, it should be :
angular.module('Productportfolio', ['ngRoute', 'ProductService', 'ProductCtrl'])
.config(['$routeProvider', '$locationProvider',
Update :
But in fact, in your case, it works even without precising the array :
angular.module('Productportfolio', ['ngRoute', 'ProductService', 'ProductCtrl'])
.config(
I updated the plunker and the app.js with both versions. I have the impression that the array is not mandatory (any longer). So, it seems better to ignore that parameter, especially, if with bad value, it may create side-effects.
Here the plunker with corrections (ordered lib, typos and config function called) :
http://plnkr.co/edit/NTn6Zmav5RX4V8zgHPOG?p=preview
I have removed $locationProvider.hashPrefix('!') as not suitable for the url you are using. See #AndreaM16 answer for that.
Besides, you have not declared your service you want to use in your controller.
app.js
angular.module('Productportfolio', ['ngRoute'])
.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'ProductCtrl'
})
.when('/private', {
templateUrl: 'private.html',
controller: 'ProductCtrl'
})
.otherwise({
redirectTo: '/home',
controller: 'ProductCtrl'
});
}]
);
or app.js without the array parameter in config function :
angular.module('Productportfolio', ['ngRoute'])
.config(
function ($routeProvider, $locationProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'ProductCtrl'
})
.when('/private', {
templateUrl: 'private.html',
controller: 'ProductCtrl'
})
.otherwise({
redirectTo: '/home',
controller: 'ProductCtrl'
});
// $locationProvider.hashPrefix('!');
}
);
index.html :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<!--Bootstrap-->
<script data-require="jquery#*" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<script src="https://www.atlasestateagents.co.uk/javascript/tether.min.js"></script><!-- Tether for Bootstrap -->
<link data-require="bootstrap#*" data-semver="4.0.0-alpha.2" rel="stylesheet" href="https://cdn.rawgit.com/twbs/bootstrap/v4-dev/dist/css/bootstrap.css" />
<script data-require="bootstrap#*" data-semver="4.0.0-alpha.2" src="https://cdn.rawgit.com/twbs/bootstrap/v4-dev/dist/js/bootstrap.js"></script>
<!--AngularJS-->
<script data-require="angularjs#1.5.8" data-semver="1.5.8" src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"></script>
<script data-require="angular-route#*" data-semver="1.5.8" src="https://code.angularjs.org/1.5.8/angular-route.js"></script>
<!--own js -->
<script src="app.js"></script>
<!--Controller -->
<script src="ProductCtrl.js"></script>
<!--Services -->
<!--Direktives-->
</head>
<body ng-app="Productportfolio">
<ul>
<li>
Home
</li>
<li>
Log in
</li>
</ul>
<div ng-view></div>
</body>
</html>
The order of loading java script files is very important. Load in the following order:
<link data-require="bootstrap#*" data-semver="4.0.0-alpha.2" rel="stylesheet"
href="https://cdn.rawgit.com/twbs/bootstrap/v4-dev/dist/css/bootstrap.css" />
<script data-require="jquery#*" data-semver="3.0.0"
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<script src="https://www.atlasestateagents.co.uk/javascript/tether.min.js"></script>
<script data-require="bootstrap#*" data-semver="4.0.0-alpha.2"
src="https://cdn.rawgit.com/twbs/bootstrap/v4-dev/dist/js/bootstrap.js"></script>
<!--AngularJS-->
<script data-require="angularjs#1.5.8" data-semver="1.5.8"
src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"></script>
<script data-require="angular-route#*" data-semver="1.5.8"
src="https://code.angularjs.org/1.5.8/angular-route.js"></script>
It means that you are loading Bootstrap.js files, but Bootstrap cannot work without jQuery library. So it means you should load jQuery at first, then Bootstrap.js. And other libraries should be reordered(I've shown in an example above).
In addition, you can use Console in your browser to see whether there are errors and what errors you have.

Why is my page not picking up my controller

I am getting to understand routing and I have a simple application with a couple buttons at the top in the header area. The buttons work well and display the correct information but I've directed that one of the pages (directory.html) use the "myController" controller that I created but instead it continues to give me the curley braces and not the actual scope data. Can someone tell me what I'm doing wrong?
HTML
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<title>Sample app</title>
<link href="content/css/styles.css" rel="stylesheet" type="text/css" />
<script src="app/lib/angular.min.js"></script>
<script src="app/lib/angular-route.min.js"></script>
<script src="app/app.js"></script>
</head>
<body>
<header ng-include="'header.html'"></header>
<main ng-view></main>
</body>
</html>
JS
angular.module('myApp', ['ngRoute'])
.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/home', {
templateUrl: 'views/home.html'
})
.when('/directory', {
templateUrl: 'views/directory.html',
//since this page requires a controller
controller: 'myController'
})
.otherwise({
redirectTo: '/home'
});
}]);
angular.module('myApp', [])
.controller('myController', function($scope) {
$scope.message = ("Hello World");
});
Directory.html
<p>This is my directory page.</p>
<p>{{message}}</p>
Header.html
<div id="menu-bar">
<h1>My Sample App</h1>
<ul>
<li>Home</li>
<li>Directory</li>
</ul>
</div>
Your js file is invalid.
angular.module('myApp', ['ngRoute'])
.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/home', {
templateUrl: 'views/home.html'
})
.when('/directory', {
templateUrl: 'views/directory.html',
//since this page requires a controller
controller: 'myController'
})
.otherwise({
redirectTo: '/home'
});
}]);
angular.module('myApp', [])
.controller('myController', function($scope) {
$scope.message = ("Hello World");
});
You have placed your controller inside the config module...

Using Angular route in webapi application

I'm not sure how can I implement proper Angular routing in web api application. I'm able to open the pages using this approach: http://localhost:52876/HTML/app/borrower.html
The Angular controller loads fine and all functionality is there from the angular side.
Now, I want to be able to open the views in a bit better view, using ng-route, so for example http://localhost:52876/HTML/app/borrower.html will become http://localhost:52876/borrower.
I included the ng-route.js file in the html files which I'm using in my angular app.
Also in app.js I have this:
'use strict';
var modules = [
'app.controllers',
'LoanAdminApplicationController',
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'ui.router',
'LocalStorageModule',
'angular-loading-bar'
];
var app = angular.module('app', modules);
app.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when("/home", {
controller: "homeController",
templateUrl: "/app/views/home.html"
});
$routeProvider.when("/login", {
controller: "loginController",
templateUrl: "/HTML/login.html"
});
$routeProvider.when("/signup", {
controller: "signupController",
templateUrl: "/app/views/signup.html"
});
$routeProvider.when("/register", {
controller: "signupController",
templateUrl: "/app/views/register.html"
});
$routeProvider.when("/refresh", {
controller: "refreshController",
templateUrl: "/app/views/refresh.html"
});
$routeProvider.when("/tokens", {
controller: "tokensManagerController",
templateUrl: "/app/views/tokens.html"
});
$routeProvider.when("/borrower", {
controller: "borrowerController",
templateUrl: "/HTML/app/borrower.html"
});
$routeProvider.otherwise({ redirectTo: "/home" });
});
The html markup (I removed the content):
<!DOCTYPE html>
<html ng-app="app">
<head>
</head>
<body ng-controller="BorrowerQuickQuoteApplication">
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="/assets/js/jquery.min.js"></script>
<script src="/assets/js/modernizr.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="/assets/js/bootstrap.min.js"></script>
<script src="/Scripts/angular.js"></script>
<script src="/Scripts/angular-cookies.min.js"></script>
<script src="/Scripts/angular-resource.min.js"></script>
<script src="/Scripts/angular-sanitize.min.js"></script>
<script src="/Scripts/angular-route.min.js"></script>
<script src="/Scripts/angular-ui-router.min.js"></script>
<script src="/Angular/controllers.js"></script>
<script src="/Angular/LoanApplicationController.js"></script>
<script src="/Angular/services.js"></script>
<script src="/Scripts/angular-local-storage.min.js"></script>
<script src="/Scripts/loading-bar.min.js"></script>
<script src="/Angular/app.js"></script>
</body>
</html>
Any idea what I need to do in order to make this working?
Should I modify the RouteConfig.cs file or I need to do anything else as well?
You don't navigate with the file name as you are doing that's angular route job to do for example
$routeProvider.when("/borrower", {
controller: "borrowerController",
templateUrl: "/HTML/app/borrower.html"
});
when you go to localhost:8080/yourapp/borrower
and you need ng-view in your index.html
Like this
<div ng-view></div>
your pages will be shown here.
router will look that you are requesting for the borrower and it will take you to the /HTML/app/borrower.html
You are using html five mode that means you need server side routing to so it can fall to index.html every time so your url can be without hash.

Getting $injector:modulerr after including ['ngRoute']

Having a $injector:modulerr error after including ngRoute. Using AngularJS 1.2.26
var app = angular.module('myApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/', {controller: indexController1, templateURL: 'index1.html'});
$routeProvider.when('/view/:id', {controller: indexController2, templateURL: 'index2.html'});
$routeProvider.otherwise({redirectTo: '/'});
});
app.controller('indexController1', function ($scope) { .... }
app.controller('indexController2', function ($scope, $routeParams) { .... }
html template
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-route.min.js"></script>
<script src="app.js">
</head>
<body>
<div ng-view></div>
</body>
</html>
There are some problems in your code:
The .config
You should use nested .when instead of again define $routeProvider
Name of the controllers between quotes
Missing closing ); in controllers
var app = angular.module('myApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'index1.html',
controller: 'indexController1'
})
.when('/view/:id', {
templateUrl: 'index2.html',
controller: 'indexController2'
})
.otherwise({
redirectTo: '/'
});
});
app.controller('indexController1', function ($scope) {
});
app.controller('indexController2', function ($scope, $routeParams) {
});
The html
Missing </script> close tag.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-route.min.js"></script>
<script src="app.js"></script>
Check here a working example ngRoute

Resources