Unable to load controller within $routeProvider in AngularJS - angularjs

This is my very first AngularJs app and created it after going through many examples on the web but I am doing something wrong here. It is highly likely because files are stored in dedicated folders. The HomeView.html template gets loaded fine but the controller doesn't. I mean I cannot get greetingMessage printed in the template. All I see is {{ greetingMessage }} instead of "Welcome!". What am I missing?
Error
Error: [$controller:ctrlreg] http://errors.angularjs.org/1.6.4/$controller/ctrlreg?p0=HomeController
App Structure
app
conponents
home
HomeView.html
HomeController.js
...
...
index.js
index.html
index.html
<body ng-app="myApp">
<h3>AngularJS</h3>
<hr />
<p>Home</p>
<div ng-view></div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.min.js"></script>
<script src="index.js"></script>
</body>
index.js
var module = angular.module('myApp', ['ngRoute']);
module.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'components/home/HomeView.html',
controller: 'HomeController'
// I tried -> controller: 'components/home/HomeController'
})
.otherwise({
redirectTo: '/'
});
});
HomeView.html
<div ng-controller="HomeController">
<h4>Home</h4>
<p>{{ greetingMessage }}</p>
</div>
HomeController.js
var module = angular.module('myApp', []);
module.controller('HomeController', [
'$scope',
function(
$scope
) {
$scope.greetingMessage = 'Welcome!';
}]);

The main reason is you haven't referred homeController.js on index.html, it should place right after index.js. This will not solve your issue. The other thing I'd like to mention is, you shouldn't be creating myApp module again while registering your controller with your myApp module. By declaring new module will flush out former registered component. So just use module getter like angular.module('myApp') and append further components to it.
<script src="components/home/HomeController.js">
Code
angular.module('myApp')
.controller('HomeController', [ '$scope',
function($scope) {
$scope.greetingMessage = 'Welcome!';
}
]);

You must be attach app file and next attache your controller file in your hoem page or master page.
This example helped you
Angular js routing

Related

Losing scope between angular modules using ng-view

I seem to be losing scope on my angular controller when I am trying to abstract my Angularjs modules.
It works fine if i use my app module, but as soon as I change the home.js module to app.layout, $scope no longer works.
Can anybody spot an issue here?
_Layout.html (left out includes and head)
<body class="docs-body" ng-app="app">
<div layout="column" ng-cloak>
<section layout="row" flex>
<div ng-include="'App/layout/sidenav.html'"></div>
<md-content class="_md layout-column flex" layout="column" flex="">
<div ng-include="'App/layout/toolbar.html'"></div>
<div class="container body-content">
#RenderBody()
</div>
</md-content>
</section>
</div>
</body>
#RenderBody() brings up Index.html
<!-- this is where content will be injected -->
<div ng-view></div>
Home.html
<div>
<h1>Home Page</h1>
<p>{{ message }}</p>
</div>
My app.js
angular.
.module('app', [
'app.core',
'app.layout',
]);
})();
layout.module.js
(function () {
'use strict';
angular.module('app.layout', [
'ngAnimate',
'ngMaterial',
'ngAria'
]);
})();
core.module.js
(function () {
'use strict';
angular.module('app.core', [
'ngRoute'
]);
})();
and route.js:
angular.module('app.core')
.config(function ($routeProvider, $locationProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl: 'App/layout/home.html',
controller: 'home'
});// End routeprovider
})// end config
And Finally the culprit... Home.js
(function () {
'use strict';
console.log('registering controller home before Angular');
angular
.module('app.layout')
.controller('home', home);
home.$inject = ['$scope'];
function home($scope) {
console.log('registering controller home');
// create a message to display in our view
$scope.message = 'Everyone come and see how good I look!';
}
})();
Now, When i have
.module('app);
.controller('home', home);
on home.js, the $scope.message displays
'Everyone come and see how good I look!'
but if i have
.module('app.layout')
.controller('home', home);
it displays
{{message}}
I know I'm losing scope somehow here, but I cant figure out how to fix it! Do I need to declare the controller again outside of the Router?
I think Angular not able to get your home controller. You should inject app.layout in app.core module.
angular.module('app.core', ['app.layout'])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl: 'App/layout/home.html',
controller: 'home'
});// End routeprovider
})// end config
angular.
.module('app.layout',[]).controller();
The solution was rather frustrating. Using Visual Studio's Bundle config, It was adding the home.js file in before it compiled the module files. In doing so, when it tried to build and register the controller, It couldn't find the module. solution was to build all modules first then build controllers by specifying build order in the bundle config.

Angular controller not binding to view

I have an Angular controller defined something like
mainCtrl.js
angular.module("mainCtrl", [])
.controller("mainController", function ($rootScope, $location, Auth) {
var vm = this;
vm.testStr = "If you see this, mainController is active on your page";
.
.
.
Here Auth is an angular service defined to handle authentication and it doesn't put the testStr variable behind authentication.
A view defined tries to bind the variable testStr as bellow
index.html
<html>
<head>
<base href="/">
<!-- load angular and angular-route via CDN -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-route.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-animate.js"></script>
</head>
<body ng-app="userApp" ng-controller="mainController as main">
<main class="container">
<!-- ANGULAR VIEWS -->
<div><h3>{{main.testStr}}</h3></div>
<div ng-view></div>
</main>
</body>
</html>
But when the index is loaded the value of testString doesn't appear on the page. Instead {{main.testStr}} appears.
I am assuming it is not a must to use $scope and couldn't find what I am doing wrong.
Thanks in advance, for your help.
Edit
There are other files involved that I didn't mention here. Now I can see their relevance.
The app module,
app.js
angular.module("userApp", ["ngAnimate", "app.routes",
"authService", "mainCtrl",
"employeeCtrl", "employeeService"])
// application configuration to integrate token into requests
.config(function ($httpProvider) {
// attach our auth interceptor to the http requests
$httpProvider.interceptors.push("AuthInterceptor");
});
module for routing
app.route.js
angular.module("app.routes", ["ngRoute"])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
// route for the home page
.when("/", {
templateUrl: "app/views/pages/home.html"
})
// login page
.when("/login", {
templateUrl: "app/views/pages/login.html",
controller: "mainController",
controllerAs: "login"
})
// show all employees
.when("/employees", {
templateUrl: "app/views/pages/employees/all.html",
controller: "employeeController",
controllerAs: "employee"
})
// form to create a new user
// same view as edit page
.when("/employees/create", {
templateUrl: "app/views/pages/employees/single.html",
controller: "employeeCreateController",
controllerAs: "employee"
})
// page to edit a user
.when("/employees/:employee_id", {
templateUrl: "app/views/pages/employees/single.html",
controller: "employeeEditController",
controllerAs: "employee"
});
$locationProvider.html5Mode(true);
});
You have declared the Module name as mainCtrl
angular.module("mainCtrl", [])
but using ng-app as userApp
Change your module like this,
angular.module("userApp", [])
Your module name is wrong. It should be userApp instead of mainCtrl. See a working example below:
var myApp = angular.module("userApp", []);
myApp.controller("mainController", function($scope) {
var vm = this;
vm.testStr = "Hello";
});
<html>
<head>
<base href="/">
<!-- load angular and angular-route via CDN -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-route.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-animate.js"></script>
</head>
<body ng-app="userApp" ng-controller="mainController as main">
<main class="container">
<!-- ANGULAR VIEWS -->
<div>
<h3>{{main.testStr}}</h3>
</div>
<div ng-view></div>
</main>
</body>
</html>

Template with its own controller for angular js

I am kind of new to angular JS and this might be the simple question but i am stuck on this.
What i am trying to do is, I have one page and on that page I want to add a template. My template is kind of dynamic and have it's own controller. My code is something like this..
-- Main Page HTML --
<html ng-app="myApp">
<body ng-controller="MyAppCtrl">
<my-component>
</my-component>
</body>
</html>
-- Main page JS --
var myAppModule = angular.module('myApp');
myAppModule.controller('MyAppCtrl', function ($scope) {
})
.directive('myComponent', function () {
return {
restrict: 'E',
templateUrl: 'myComponent.aspx'
};
});
-- Template(myComponent.aspx) --
<html>
<!-- include template script -->
<body ng-controller="ComponentCtrl">
<div ng-click="showAlert()">
myBtn
</div>
</body>
</html>
-- Template page JS --
var templareModule = angular.module('myApp', []);
templareModule.controller('ComponentCtrl', function ($scope, $http) {
$scope.showAlert = function () {
alert("clicked");
}
});
So for this I am unable to get alert on click.
Thanks in advance.
You really don't need to create a custom directive to be able to do what you describe in your question and since you're a beginner I would suggest you start simple and do without the directive. You will need to use the ng-view tag and routing. There are some other minor issues with your code, some of which were already pointed out by others in the comments. The following code worked for me.
index.html:
<html ng-app="myApp">
<body>
<h1>Test</h1>
<div ng-view></div>
<script> (Insert paths to required Angular scripts and your JS files)</script>
</body>
</html>
App JS file:
Note: You will need to download the ngRoute JavaScript file from Angular's website and include it in your project to get the routing to work correctly. (Go to Downloads on their website, pick your version of Angular, then download ngRoute)
angular.module('myApp', [ 'ngRoute' ])
.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'myComponent.aspx',
controller: 'ComponentCtrl'
})
}])
.controller('ComponentCtrl', function ($scope) {
$scope.showAlert = function () {
alert("clicked");
}
});
myComponent.aspx:
<div class="ComponentCtrl">
<div ng-click="showAlert()">
myBtn
</div>
</div>
Let me know if you have questions or are still unable to get it to work. I would also suggest you check out some tutorial videos on Egghead.io's website. It helped me figure out the basics of Angular.

Route provider cannot access controllers definitions

I am trying to learn the route features of angularJS, but what I have happened so far doesn't work.
If I ever click Load, Display, or Play (in my example: the links to possible action urls)
then <div ng-view></div> still exist in the DOM (when I inspect it) , moreover it is not replaced by the related html partial file as indicated in the templateUrl of the route provider.
The Chromium log console displays an error:
Uncaught ReferenceError: LoadCtrl is not defined from my_app
If I put all the when in comments while defining the route provider, then the error is no longer thrown.
So I have thought it could depend upon the order of definition of the controllers regarding the definition of the route provider. So I have tried putting them before, or after, also in a seperate controllers.js file... But that doesn't change anything.
I suppose I am making a obvious mistake, but I cannot catch it. Any idea ?
content of index.html:
<!DOCTYPE html>
<html ng-app="my_app">
<body>
<section class="section_command">
<ul>
<li>Load file</li>
<li>Display file</li>
<li>Play file</li>
</ul>
</section>
<section class="section_content">
<div ng-view></div>
</section>
<script type="text/javascript" src="js/angular.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
content of app.js:
var app = angular.module('my_app',[]);
app.controller('LoadCtrl', function($scope, $http, $routeParams){});
app.controller('DisplayCtrl', function($scope, $http, $routeParams){});
app.controller('PlayCtrl', function($scope, $http, $routeParams){});
app.config(['$routeProvider', function($routeProvider)
{
$routeProvider.
when('/load', {templateUrl: 'partials/load.html', controller: LoadCtrl}).
when('/display', {templateUrl: 'partials/display.html', controller: DisplayCtrl}).
when('/play', {templateUrl: 'partials/play.html', controller: PlayCtrl}).
otherwise({redirectTo: '/'});
}]);
the partial html files are as simple as can be:
load.html : <span>Loading</span>
display.html : <span>Displaying</span>
play.html : <span>Playing</span>
I'm pretty sure you need to address your controllers by their string name:
when('/load', {templateUrl: 'partials/load.html', controller: 'LoadCtrl'}).

simple angularjs app view not loading

I'm trying to get into angularJS by writing the most basic app. However I'm unable to get even this small amount of code working - the controller doesn't seem to be displaying any of the views. This is almost a direct copy from a popular angularjs video I saw online. I have a feeling its not something big, and my guess is that I possibly have something wrong with the ng-view.
Any insight on what I'm doing wrong would be helpful.
index.html
<!doctype html>
<html ng-app="fastsql">
<head>
</head>
<body>
<div class="well">
<div ng-view></div>
</div>
<script src="angular.min.js"></script>
<script src="fastsql.js"></script>
</body>
</html>
fastsql.js
// setup fastsql as angular app "module"
var fastsql = angular.module("fastsql", []);
// set routeProvider rules in .config()
fastsql.config(function($routeProvider) {
// set what views are displayed for each change in the URL.
$routeProvider
.when("/", { controller: 'loginCntl', templateURL: 'test.html' })
.otherwise({ redirectTo: '/' });
});
// controllers
fastsql.controller("loginCntl", function($scope) { $scope.message = "hey"; });
templateURL should have been templateUrl.
you need to pass an array into the config function, the name of the services to injected, and then the function in to which they are injected.
fastsql.config(["$routeProvider", function($routeProvider) {
// do your thing
}]);

Resources