AngularJS controller not accessed - angularjs

I am learning AngularJS and I have a problem with the controller.
This example below already worked, but it suddenly stoped without any changes that could cause that. I am not sure what is wrong.
The /templates/index.html file does not load.
This is my main index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Todolist</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- ANGULAR JS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.min.js"></script>
<script src="app/app.js"></script>
<script src="app/controllers/todolists.js"></script>
</head>
<body ng-app="app">
<div ui-view></div>
</body>
</html>
This is my app.js:
var app = angular.module('app', ['ui.router']);
app.config(function ($stateProvider) {
$stateProvider
.state('/', {
url: "/",
templateUrl: "app/templates/index.html",
controller: 'todolists',
});
});
This is my todolists controller:
var app = angular.module('app');
var controllers = {};
console.log("test");
controllers.todolists = function ($scope, $http) {
console.log("test1");
$http.get('http://localhost:8888/todolist/rest/entries/index.json').
then(function(response) {
console.log(response.data);
$scope.data = response.data;
});
};
app.controller(controllers);
console.log("test") writes to console, but console.log("test1") does not, so the controller is not accessed.
Please take a look and let me know if you have and tips about what could be wrong.
Thanks, Grega

You need to register a name for the controller is the problem. Ive registered the name 'todolistCtrl' which is the first argument needed for the controller registration method. the second argument is the function controllers.todolists.
you can then reference todolistCtrl within you State Provider.
controller
var controllers = {};
console.log("test");
controllers.todolists = function ($scope, $http) {
$http.get('http://localhost:8888/todolist/rest/entries/index.json').
then(function(response) {
console.log(response.data);
$scope.data = response.data;
});
};
angular.module('app')
.controller('todolistCtrl', controllers.todolists);
app
var app = angular.module('app', ['ui.router']);
app.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('/', {
url: "/",
templateUrl: "index.html",
controller: 'todolistCtrl',
});
});
Plunker
Example

Related

Angular Routing is not working even after controller is defined in main page

I have defined my controller in main page but still i keep getting this error. [$controller:ctrlreg] http://errors.angularjs.org/1.6.10/$controller/ctrlreg?p0=NavCtrl
app.module.js
var app = angular.module("myApp", ["ngRoute"]);
routeConfig.js
angular.module("myApp", ["ngRoute"]).config(function ($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'Home.html',
controller: 'HomeController'
})
.when('/blog', {
templateUrl: 'Blog.html',
controller: 'BlogController'
})
.otherwise({
redirectTo: '/home',
controller: 'HomeController',
});
});
TestScript.js
angular.module("myApp", ["ngRoute"]).controller('NavCtrl',
['$scope', '$location', function ($scope, $location) {
$scope.navClass = function (page) {
var currentRoute = $location.path().substring(1) || 'home';
return page === currentRoute ? 'active' : '';
};
$scope.loadHome = function () {
$location.url('/home');
};
$scope.loadBlog = function () {
$location.url('/blog');
};
}]);
angular.module("myApp", ["ngRoute"]).controller('HomeController', function ($scope, $compile) {
console.log('inside home controller');
});
angular.module("myApp", ["ngRoute"]).controller('BlogController', function ($scope, $compile) {
console.log('inside blog controller');
});
Home.html
<div>
Home Navigation panel.
</div>
Blog.html
<div>
Blog Navigation panel.
</div>
MainPage.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="myApp">
<head>
<title></title>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href='//netdna.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css' rel='stylesheet' />
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="scripts/angular.min.js"></script>
<script src="scripts/angular-route.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<!--<script src="Views/Config/app.module.js"></script>
<script src="Views/Directives/Ecommerce/controller.js"></script>
<script src="Views/Directives/Ecommerce/directive.js"></script>-->
<script src="TestScript.js"></script>
<link rel="stylesheet" href="Content/EcommerceStyleSheet.css" type="text/css" />
</head>
<body ng-controller="NavCtrl">
<!--<my-Directive></my-Directive>-->
Home<br />
Blog
<br />
<div ng-view></div>
</body>
</html>
Please suggest if i am missing something or do i need to inject something to making routing work
It's just as the #Lex said,
please remove ['ngRoute'] from all of the controllers in your TestScript.js and include/uncomment your app.module.js and routeConfig.js scripts in your MainPage.html
So that you may achieve something like this if it's all put together;
var app = angular.module("myApp", ["ngRoute"]); // from app.module
angular.module("myApp", ["ngRoute"]).config(function ($routeProvider) { // from routeConfig
$routeProvider
.when('/home', {
templateUrl: 'Home.html',
controller: 'HomeController'
})
.when('/blog', {
templateUrl: 'Blog.html',
controller: 'BlogController'
})
.otherwise({
redirectTo: '/home',
controller: 'HomeController',
});
});
angular.module("myApp").controller('NavCtrl',
['$scope', '$location', function ($scope, $location) { // from TestScript
$scope.navClass = function (page) {
var currentRoute = $location.path().substring(1) || 'home';
return page === currentRoute ? 'active' : '';
};
$scope.loadHome = function () {
$location.url('/home');
};
$scope.loadBlog = function () {
$location.url('/blog');
};
}]);
angular.module("myApp").controller('HomeController', function ($scope, $compile) {
console.log('inside home controller');
});
angular.module("myApp").controller('BlogController', function ($scope, $compile) {
console.log('inside blog controller');
});

Angular routing issue unable to perform events

I am having two html files in my app folder as follows
app
| - Home.html
| - Folder - Employee.html and Employee.controller.js
| - app.module.js
| - app.route.js
My Home.html is as follows
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="/Scripts/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.js"></script>
<script src="/app/app.module.js"></script>
<script src="/app/app.routes.js"></script>
<script src="/app/Folder/Employee.controller.controller.js"></script>
</head>
<body ng-app="employeeModule">
<ui-view>
<i>Some content will load here!</i>
</ui-view>
Link
</body>
</html>
My app.module.js is as follows
(function () {
"use strict";
angular.module('employeeModule', ['ui.router']);
})();
My app.route.js is as follows
(function () {
'use strict';
angular.module('employeeModule').config(employeeAppConfiguration);
function employeeAppConfiguration($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.hashPrefix('');
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '',
abstract: true,
views: {
'home': {
templateUrl: '/app/Home.html'
}
}
})
.state('home.employee', {
url: '/employee',
templateUrl: '/app/Folder/Employee.html',
controller: 'employeeController',
controllerAs: 'empCtrl'
});
}
})();
My controller is as follows
(function () {
'use strict';
angular.module('employeeModule')
.controller('employeeController', employeeController);
function employeeController() {
var ctrl = this;
ctrl.employee;
ctrl.submitEmployee= submitEmployee;
function submitEmployee(employee) {
}
};
});
I am unable to see the submitEmployee function called on my submit click this is is my html
Add
Can some one help me where I am going wrong
probably address of youre controller is misspelled
<script src="/app/Folder/Employee.controller.controller.js"></script>
incorrect controller file name. Change it to<script src="/app/Folder/Employee.controller.js"></script>

Routing is not working with Angular UI Router

I have following code to setup the routing using Angular UI Router:
index.html
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8" />
<title>AngularJS Routing</title>
<script src="js/angular.js"></script>
<script src="js/angular-ui-router.min.js"></script>
<base href="/" />
<script>
'use strict'
var myApp = angular.module('myApp', ['myApp.Controllers', 'ui.router']);
var myAppControllers = angular.module('myApp.Controllers', []);
myApp.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider.state('view1', {
url: '/view1',
controller: 'Controller1',
templateUrl: '/partials/view1.html'
}).state('view2', {
url: '/view2/:firstname/:lastname',
controller: 'Controller2',
resolve: {
names: function () {
return ['Misko', 'Voita', 'Brad'];
},
},
templateUrl: '/partials/view2.html'
});
$urlRouterProvider.otherwise('/view1');
$locationProvider.html5Mode(true);
});
myAppControllers.controller('Controller1', function ($scope, $location, $state) {
$scope.loadView2 = function () {
$state.go('view2', {
firstname: $scope.firstname,
lastname: $scope.lastname
});
}
});
myAppControllers.controller('Controller2', function ($scope, $stateParams, names) {
$scope.firstname = $stateParams.firstname;
$scope.lastname = $stateParams.lastname;
$scope.names = names;
});
</script>
</head>
<body>
<ul class="menu">
<li><a ui-sref="view1">View1</a></li>
<li><a ui-sref="view2">View2</a></li>
</ul>
</body>
</html>
I checked multiple times and I don't see any errors in console window of the chrome browser.
Can anyone help me to resolve this issue?
There's no ui-view directive in your html code. So the views have nowhere to render. You should add at least
<div ui-view></div>
to show the content of the views.

AngularJS controller function not called

So I have my index page:
<!DOCTYPE html>
<html ng-app="application" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="Content/bootstrap.min.css" rel="stylesheet" />
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/angular-route.min.js"></script>
<script src="app/app.js"></script>
</head>
<body>
<!-- Place where the page will be rendered at -->
<div ng-view>
</div>
</body>
</html>
The application looks like this:
var application = angular.module('application', ["ngRoute"]);
application.config(["$routeProvider", "$locationProvider",
function ($routeProvider, $locationProvider) {
$routeProvider
.when("/home", {
templateUrl: "app/ListContactsForm/lcTemplate.html",
controller: "HomeController"
})
.otherwise({
redirectTo: "/home"
});
//$locationProvider.html5Mode(true);
}]);
application.controller("HomeController",
["$scope", "$location", "DataService",
function ($scope, $location, DataService) {
alert("home hit!");
}]);
The lcTemplate.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>aaaa</title>
</head>
<body>
I'm here!!
</body>
</html>
The problem is that the lcTemplate is rendered, i get the "I'm here!!" message, but he HomeController function is never called. Why is that so?
The problem was in injecting the DataService which did not exist (I removed the service).
Error: [$injector:unpr] http://errors.angularjs.org/1.3.12/$injector/unpr?p0=DataServiceProvider%20%3C-%20DataService%20%3C-%20HomeController
Changes which needed to be done were all in the application code:
var application = angular.module('application', ["ngRoute"]);
application.config(["$routeProvider", "$locationProvider",
function ($routeProvider, $locationProvider) {
$routeProvider
.when("/home", {
templateUrl: "app/ListContactsForm/lcTemplate.html",
controller: "HomeController"
})
.otherwise({
redirectTo: "/home"
});
//$locationProvider.html5Mode(true);
}]);
application.controller("HomeController",
["$scope", "$location",
function ($scope, $location) {
alert("home hit!");
}]);
You have to remove the complete HTML definition from the template because the view is rendered inside
<div ng-view>
</div>
lcTemplate.html: should be like
<div>I'm here!!</div>
You have not declare "DataService". for example: I have my services in model_services.js
var services = angular.module('ModelServices');
services.factory('DataService', ['$resource', function($resource){
var DataService = $resource('/api/data/:id', {id: "#id" });
return DataService;
}]);
This method is for call to any consuming services. '/api/data/:id' is your API Rest path.
After that you have to add your module in your config application, for this example 'ModelServices'
var application = angular.module('application', ["ngRoute", "ModelServices"]);
Now you can call your "DataService" from the controller
application.controller("HomeController",
["$scope", "$location", "DataService",
function ($scope, $location, DataService) {
console.log("home hit!");
}]);
I have not idea if you can call "alert" from controller but I'm sure can you use console.log instead.
As you say #omegasbk "The problem was in injecting the DataService which did not exist (I removed the service)." if you have not declare your module that contain your "DataService" object in your application then you can not use this in your controller.

AngularJS subdirectory routing not working, with <base> tag applied

I've got an incredibly simple AngularJS template, I'm trying to get routing to work but when I load the page I'm just seeing the H1 tag from my index.html.
My app is in a sub directory, /angular-route/, and I know that the partials exist, I can visit /angular-route/partials/interest.html and the page renders fine.
Have I missed something really basic here?
<html>
<head ng-app="myApp">
<title>AngularJS Routing</title>
<base href="/angular-route/" />
</head>
<body>
<h1>AngularJS Routing</h1>
<div ng-view></div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<script>
'use strict';
var myApp = angular.module('myApp', []).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/interest', {
templateUrl: 'partials/interest.html',
controller: 'InterestCtrl'
}).
when('/catalogue', {
templateUrl: 'partials/catalogue.html',
controller: 'CatalogueCtrl'
}).
otherwise({redirectTo: '/interest'});
}]);
myApp.controller('InterestCtrl', function($scope, $routeParams) {
console.log('InterestCtrl');
});
myApp.controller('CatalogueCtrl', function($scope, $routeParams) {
console.log('CatalogueCtrl');
});
</script>
Beside the base tag, which you will need, you've also placed the ng-app directive on wrong element (head). In your code, the Application is initialized only inside the header. Rest of the HTML is ignored by Angular.
WORKING PLUNKER
<html ng-app="myApp">
<head>
<title>AngularJS Routing</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script type="text/ng-template" id="partials/interest.html">
<h2>Inereset</h2>
</script>
<script type="text/ng-template" id="partials/catalogue.html">
<h2>Catalogue</h2>
</script>
</head>
<body>
<h1>AngularJS Routing</h1>
<ul>
<li>Interest</li>
<li>Catalogue</li>
</ul>
<div ng-view></div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<script>
'use strict';
var myApp = angular.module('myApp', []).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/interest', {
templateUrl: 'partials/interest.html',
controller: 'InterestCtrl'
}).
when('/catalogue', {
templateUrl: 'partials/catalogue.html',
controller: 'CatalogueCtrl'
}).
otherwise({redirectTo: '/interest'});
}]);
myApp.controller('InterestCtrl', function($scope, $routeParams) {
console.log('InterestCtrl');
});
myApp.controller('CatalogueCtrl', function($scope, $routeParams) {
console.log('CatalogueCtrl');
});
</script>
</body>
</html
Following configuration worked for me!
Let's say we want to access our app using http://localhost:8000/app/
Then have your base tag with the following highlighted

Resources