Angular controller not binding to view - angularjs

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>

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 ng-view not showing routed pages

The ng-view is not showing pages and routing doesn't seem to work but it is loading the angular-route.min.js in the browsers console/network.
The file structure is folders -> css, fonts, js, pages. there are 2 files in the root which are app.js and index.html and inside the pages folder are 2 more files which are the main.html and second.html which are supposed to be added to the ng-view parts but wont load.
When clicking on a link for the main.html content it comes back with http://127.0.0.1/main and completely ignores the /pages folder
**updated code, got the first page to load its content but the second one doesn't and there are no errors in the console so assumably I have the wrong href path?
Header Scripts
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="//code.angularjs.org/1.6.1/angular-route.min.js"></script>
<script src="app.js"></script>
HTML
<div class="row">
Main Content
Second Content
</div>
<div class="row">
<div class="col-md-12">
<div ng-view></div>
</div>
</div>
<hr>
</div>
JS
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function($routeProvider) {
$routeProvider
.when('/', {
templateURL: 'pages/main.html',
controller: 'mainController'
})
.when('/second', {
templateURL: 'pages/second.html',
controller: 'secondController'
})
});
myApp.controller('mainController', ['$scope', function($scope) {
}]);
myApp.controller('secondController', ['$scope', '$log', function($scope, $log) {
}]);
Use templateUrl instead of templateURL.
In your html use #/main.
Don't use tow ng-views
JS code
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function($routeProvider) {
$routeProvider
.when('/main', {
templateUrl: 'main.html',
controller: 'mainController'
})
.when('/second', {
templateUrl: 'second.html',
controller: 'secondController'
})
});
myApp.controller('mainController', ['$scope', function($scope) {
$scope.name = "world"
}]);
myApp.controller('secondController', ['$scope', '$log', function($scope, $log) {
}]);
HTML code
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<script src="//code.angularjs.org/1.4.0/angular-route.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="mainController">
<p>Hello {{name}}!</p>
<div class="row">
Main Content
Second Content
</div>
<div class="row">
<div class="col-md-12">
<div ng-view></div>
</div>
</div>
<hr>
</body>
</html>
Here is working plunker
EDIT
Please note I have used angular version 1.4.0. If you want to use angular 1.6.1 they have changed default hash-prefix used for $location hash-bang URLs it is now ('!') instead of ('')
So you need to add this in your config phase.
myApp.config(['$locationProvider', function($locationProvider) {
$locationProvider.hashPrefix('');
}]);
now it will work with angular 1.6.1 as well
.when('/main', {
templateURL: 'pages/main.html',
controller: 'mainController'
})
or
use this url to access main page :
http://127.0.0.1/
It should work, as you have not set routing for main in config.

angularJS- initiate HTTP Call from a controller failed

I am building a website using angularJS and PHP. Website has many pages like- Home, About Us etc.
So, I have created a common header for the website which I included in my HTML view like this:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="commonController.js"></script>
<script src="homeController.js"></script>
<script src="loginController.js"></script>
<script src="app.js"></script>
</head>
<body>
<div class="header" ng-controller="CommonController"
ng-include="'header.html'"></div>
<div class="main" ng-view></div>
</body>
</html>
and the header (header.html) page looks like this:
<nav class="navbar-inverse navbar-fixed-top" role="navigation">
Home
<a href="#/notifications" >{{vm.commonId}}</a>
</nav>
and header controller has a http call which fetches user id and I am trying to show this id as a label for one of the links mentioned above (commonController.js)
(function() {
angular
.module('myApp.common', ['ngRoute'])
.factory('myCommonService', function($http) {
var baseUrl = 'api/';
return {
getBasicUserInfo:function() {
return $http.get(baseUrl + 'getBasicUserInformation');
}
};
})
.controller('CommonController', function($scope, $routeParams, myCommonService) {
var vm = this;
myCommonService.getBasicUserInfo().success(function(data) {
vm.commonId = data.id;
});
});
})();
But when I navigate through pages, header remains same. So, I'm not able to initiate that http call. There are many pages in my website.
Can this be done? I'm pretty much new to this platform.
Route (app.js)
(function() {
angular.module('myApp', [
'ngRoute',
'myApp.login',
'myApp.home',
'myApp.common'
])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/login', {
controller: 'LoginController',
templateUrl: 'loginView.html',
controllerAs: 'vm'
})
.when('/home', {
controller: 'HomeController',
templateUrl: 'homeView.html',
controllerAs: 'vm'
})
.otherwise({
redirectTo: '/login'
});
}]);
})();
P.S: I excluded other pages to reduce complexity and make my query easy to understand.
Thanks!
Seems to me all that is missing is letting the template know the scoped alias for the controller
<div class="header" ng-controller="CommonController as common"
ng-include="'header.html'"></div>
and in header.html
{{common.commonId}}
Note that I've used common instead of vm as some of your routes are using vm and it's best to avoid conflicts.
If you want to trigger an update on page navigation (ie, route change), change your CommonController to this
.controller('CommonController', function($scope, myCommonService) {
var ctrl = this;
var update = function() {
myCommonService.getBasicUserInfo().then(function(res) {
ctrl.commonId = res.data.id;
});
};
update();
$scope.$on('$routeChangeSuccess', update);
});
You should be able to do this:
.when('/login', {
controller: 'LoginController',
templateUrl: 'loginView.html',
resolve: function(){ //your code here }
controllerAs: 'vm'
})
instead of getting it from the controller
I think that your issue might be that the include can't read the controller, so instead try this:
<nav class="navbar-inverse navbar-fixed-top" role="navigation" ng-controller="CommonController as vm">
Home
<a href="#/notifications" >{{vm.commonId}}</a>
</nav>
Note that you're also missing the controllerAs syntax so I added that.
And remove ng-controller from here:
<div class="header" ng-include="'header.html'"></div>

AngularJS Add template(ng-view) without redirect to new page

I cannot realized my single page. I want add template page without redirect to new page.
My index.html file:
<!doctype html>
<html lang="en" ng-app="MyApp">
<head>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="bower_components/angular-resource/angular-resource.js"></script>
<script src="scripts/app.js"></script>
</head>
<body>
About
Contact
I want show contact and about information under this links but I see this at new page
<ng-view> </ng-view>
</body>
</html>
My app.js file with routing configuration
var app = angular.module('MyApp', [ 'ngRoute']);
app.config([ '$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'dialogManager/page-home.html',
controller: function ($scope) {}
})
// about page
.when('/about', {
templateUrl: 'dialogManager/page-about.html',
controller: function ($scope) {}
})
// contact page
.when('/contact', {
templateUrl: 'dialogManager/page-contact.html',
controller: function ($scope) {}
});
} ]);
My page-contact.html
<!-- page-contact.html -->
<h2>Contact</h2>
You may consider using ng-include instead.
As per angular documentation: https://docs.angularjs.org/api/ngRoute/directive/ngView
ngView is a directive that complements the $route service by including the rendered template of the current route into the main layout (index.html) file. Every time the current route changes, the included view changes with it according to the configuration of the $route service.
Maybe ng-view is not what you need.

Angularjs routing issue, controller not loading

I have 4 files:
index.html
logic.js
controller.js
homepage.html
index.html
<html ng-app="sample">
<head>
<script src="angular.js"></script>
</head>
<body>
<div>
<div ng-view></div>
</div>
<script src="controller.js"></script>
<script src="logic.js"></script>
</body>
</html>
logic.js
var myapp = angular.module('sample',[]);
myapp.config(function($routeProvider)
{
$routeProvider
.when('/',
{
controller:homepageCtrl,
templateUrl:'homepage.html'
});
});
controller.js
function homepageCtrl($scope){
$scope.name = "ROHIT";}
homepage.html
{{name}}
homepage.html is loading and being displayed correctly by the route but the controller is not being called here when homepage.html is loaded into index.html.
Kindly help me out with this.
Thanks
You didn't defined controller in HTML.
Add this line
<div ng-controller = "homepageCtrl">
Suppose it should be in homepage.html:
<div ng-controller = "homepageCtrl">
{{name}}
</div>
In addition, wrap your controller name with ' logic.js
[EDIT]
Add $inject to routeProvider:
myapp.config(["$routeProvider",
function($routeProvider) {
$routeProvider
.when("/", {
templateUrl: 'homepage.html',
controller: 'homepageCtrl'
});
}
]);
Controller name must be pass to $routeProvider as a string :
$routeProvider
.when('/',
{
controller:'homepageCtrl',
templateUrl:'homepage.html'
});

Resources