Trouble initializing AngularJS Controller: Cannot set property ... of undefined - javascript

I'm new to angular and working on a small project which has multiple modules loaded onto a single page as requested. Currently I'm just trying to get the application to load a parameter with the staffdetails.html module and update it with the controller. Currently it just displays
Hello
Staff Details....
{{testing}}
So the value from the controller is not being loaded. I've tried in both angular 1.2 legacy and 1.5.9 (I think the latest stable), as I know syntax has apparently changed.
Here is the index.html page.
<!-- index.html -->
<!DOCTYPE html>
<html ng-app="app">
<head>
<!-- SCROLLS -->
<!-- load bootstrap and fontawesome via CDN -->
<link rel="stylesheet" type="text/css" src="lib/bootstrap.min.css" />
<!-- SPELLS -->
<!-- load angular and angular route via CDN -->
<script src="lib/angular.min.js"></script>
<script src="lib/angular-ui-router.min.js"></script>
<script src="lib/jquery-2.1.1.min.js"></script>1
<script>
(function() {
angular.module("app", ["ui.router"]);
}());
</script>
<!-- Services -->
<!--script src="app/service/informationStorage-Service.js"</script-->
<!-- Controllers -->
<script src="app/controller/additionalfeatures-controller.js"></script>
<script src="app/controller/outcome-controller.js"></script>
<script src="app/controller/staffdetails-controller.js"></script>
<script src="app/controller/training-controller.js"></script>
<script>
$(document).ready (
function () {
var app = angular.module("app");
console.log("Index1");
app.config(["$stateProvider", "$urlRouterProvider", "$compileProvider", function ($stateProvider, $urlRouterProvider, $compileProvider) {
//$compileProvider.debugInfoEnabled(false);
$stateProvider.state(
"staffdetails", {
url: "/staffdetails",
views: {
"": {
templateUrl: "template/staffdetails.html",
controller: "StaffDetailCtrl"
}
}
}
);
console.log("Index2");
$urlRouterProvider.otherwise("");
} ]);
} ());
</script>
</head>
<body>
Hello
<!-- MAIN CONTENT AND INJECTED VIEWS -->
<div id="main">
<div ui-view ng-cloak></div>
</div>
</body>
staffdetails-controller.js
(function() {
"use strict";
var app = angular.module("app");
app.controller('StaffDetailCtrl', ['$scope', function($scope) {
console.log("StaffDetailCtrl");
function saveDetails($scope) {
$scope.testing = ["This is Working"];
};
saveDetails();
}]);
});
Finally the page which is being called as a module
<div class="container">
<p>Staff Details...</p>
<p> {{testing}} </p>
</div>

The problem is you are not passing the $scope into your saveDetails() function.
I modified your code slightly so it would work here in a snippet. But, the main change was this line:
saveDetails($scope);
See working snippet here:
<!-- index.html -->
<!DOCTYPE html>
<html ng-app="app">
<head>
<!-- SCROLLS -->
<!-- load bootstrap and fontawesome via CDN -->
<link rel="stylesheet" type="text/css" src="lib/bootstrap.min.css" />
<!-- SPELLS -->
<!-- load angular and angular route via CDN -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>
<script src="//unpkg.com/angular-ui-router/release/angular-ui-router.min.js"></script>
<!-- Controllers -->
<script>
angular.module("app", ["ui.router"]);
var app = angular.module("app");
app.controller('StaffDetailCtrl', ['$scope', function($scope) {
console.log("StaffDetailCtrl");
function saveDetails($scope) {
$scope.testing = ["This is Working"];
}
saveDetails($scope);
}]);
console.log("Index1");
app.config(["$stateProvider", "$urlRouterProvider", "$compileProvider", function ($stateProvider, $urlRouterProvider, $compileProvider) {
//$compileProvider.debugInfoEnabled(false);
$stateProvider.state(
"staffdetails", {
url: "/staffdetails",
views: {
"": {
template: '<div class="container">' +
'<p>Staff Details...</p>' +
'<p> {{testing}} </p>' +
'</div>',
controller: "StaffDetailCtrl"
}
}
}
);
console.log("Index2");
$urlRouterProvider.otherwise("/staffdetails");
} ]);
</script>
</head>
<body>
Hello
<!-- MAIN CONTENT AND INJECTED VIEWS -->
<div id="main">
<div ui-view ng-cloak></div>
</div>
</body>

Related

In AngularJS, loaded content by ui-view cannot read javascript file in parent content

I want to insert header and nav bar into index.html
When header and nav bar are in index.html, My app works well.
but seperate these files to html and try to load, ui-view do not load script files.
So logout function does not work when ui-view loaed header.html
On the other hand, css works well.
I tried to follow answers like
Angularjs does not load scripts within ng-view
or
html partial is not loaded into ui-view
but it did not help to fix my problem..
Why this situation occurred?
Please any handsome or pretty developer help me..
These are my code.
app.js
'use strict';
var mainApp = angular
.module('adminApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'ui.router'
]);
mainApp.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/admin/login');
$stateProvider
.state('root',{
url: '',
abstract: true,
views: {
'headerContainer': {
templateUrl: 'views/header.html',
controller: 'HeaderCtrl',
controllerAs: 'header'
},
'navContainer':{
templateUrl: 'views/nav.html',
controller: 'NavCtrl',
controllerAs: 'nav'
}
}
})
.state('root.login', {
...
})
});
index.html
<!DOCTYPE html>
<html ng-app="adminApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Admin</title>
<base href="/">
<!-- CSS-->
<link href="bower_components/bootstrap/dist/css/main.css" rel="stylesheet">
<!-- Font-icon css-->
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<!-- start: Favicon -->
<link href="favicon.ico" rel="shortcut icon">
<!-- end: Favicon -->
</head>
<body class="sidebar-mini fixed" ng-controller="AppCtrl">
<div class="wrapper">
<div ui-view="headerContainer"></div>
<div ui-view="navContainer"></div>
<div ui-view="appContainer"></div>
</div>
<!-- Javascripts-->
<script src="../bower_components/bootstrap/dist/js/jquery-2.1.4.js"></script>
<script src="../bower_components/angular/angular.js"></script>
<script src="../bower_components/bootstrap/dist/js/bootstrap.js"></script>
<script src="../bower_components/angular-animate/angular-animate.js"></script>
<script src="../bower_components/angular-cookies/angular-cookies.js"></script>
<script src="../bower_components/angular-resource/angular-resource.js"></script>
<script src="../bower_components/angular-route/angular-route.js"></script>
<script src="../bower_components/angular-sanitize/angular-sanitize.js"></script>
<script src="../bower_components/angular-touch/angular-touch.js"></script>
<script src="../bower_components/angular-ui-router/release/angular-ui-router.js"></script>
<script src="../bower_components/bootstrap/dist/js/main.js" ></script>
<script src="scripts/app.js"></script>
<script src="scripts/controllers/headerCtrl.js"></script>
<script src="scripts/controllers/navCtrl.js"></script>
</body>
</html>
header.html
<header class="main-header hidden-print">
<nav class="navbar navbar-static-top">
<div class="navbar-custom-menu">
<ul class="top-nav">
<li>
<a ng-click="logout();">Logout</a>
</li>
</ul>
</div>
</nav>
</header>
headerCtrl.js
mainApp.controller('HeaderCtrl', function ($scope, $cookieStore) {
$scope.logout = function () {
angular.forEach($cookies.getAll(), function (v, k) {
$cookies.remove(k);
}); // This is for remove all cookies
};
});
main.js
$('.top-nav li a').on('click', function (e) {
console.log('Clicked header li');
});
It seems like you haven't used controller alias while calling logout method
ng-click="header.logout();"
As #pankaj said you need to declare the logout method on your controller alias
ng-click="header.logout();"
And the same applies for your js. You have to reference logout with this keyword since you are using controller as syntax
mainApp.controller('HeaderCtrl', function ($scope, $cookieStore) {
var vm =this;
vm.logout = function () {
angular.forEach($cookies.getAll(), function (v, k) {
$cookies.remove(k);
}); // This is for remove all cookies
};
});
For more Info: AngularJs "controller as" syntax - clarification?

AngularJs Controller in External file and using route

I have had a look through SO and nothing has helped.
This is my app.js
var app = angular.module("qMainModule", ["ngRoute"])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when("/", {
templateUrl: 'templates/anonHome/anonHome.html',
controller: 'templates/anonHome/anonHomeController'
})
.when("/about", {
templateUrl: 'templates/anonHome/anonAbout.html',
controller: 'templates/anonHome/anonAboutController'
})
.when("/services", {
templateUrl: 'templates/anonHome/anonServices.html',
controller: '/templates/anonHome/anonServicesController'
})
.when("/contact", {
templateUrl: 'templates/anonHome/anonContact.html',
controller: '/templates/anonHome/anonContactController'
})
.when("/register", {
templateUrl: 'templates/anonHome/anonRegister.html',
controller: '/templates/anonHome/anonRegisterController'
})
.when("/login", {
templateUrl: 'templates/anonHome/anonLogin.html',
controller: '/templates/anonHome/anonLoginController'
})
$locationProvider.html5Mode(true);
})
app.controller("qMainController", function ($scope) {
$scope.Title = " Welcome to Qiao";
$scope.qNavigationTemplatePath = "/templates/topMenu/anonTopNavigation.html";
$scope.copyrightMessage = "Qiao ";
$scope.copyrightYear = new Date();
});
The routing works as expected and the partial templates are being shown but the partial templates controllers are not being recognised as a function.
The Layout Template looks like this
<!DOCTYPE html>
<html ng-app="qMainModule">
<head ng-controller="qMainController">
<base href="/" />
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Qiao :: {{Title}}</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="../css/modern-business.css" rel="stylesheet" />
<!-- Custom Fonts -->
<link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<script src="/scripts/angular.js"></script>
<script src="../scripts/angular-route.js"></script>
<script src="/app/app.js"></script>
<script src="templates/anonHome/anonHomeController.js"></script>
<!-- <link href="../styles/qiao.css" rel="stylesheet" /> -->
</head>
<body ng-controller="qMainController">
<div ng-include="qNavigationTemplatePath">
</div>
<!-- Page Content -->
<div class="container">
<ng-view></ng-view>
</div>
<!-- Footer -->
<footer>
<div class="row">
<div class="col-lg-12" ng-controller="qMainController">
Copyright © {{copyrightMessage}} {{copyrightYear | date:'yyyy'}}
</div>
</div>
</footer>
<div >
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<!-- Script to Activate the Carousel -->
<script>
$('.carousel').carousel({
interval: 5000 //changes the speed
})
</script>
</div>
</body>
</html>
The partial template looks like this:
<script src="anonHomeController.js"></script>
<div ng-controller="anonHomeController">
<h1>{{Title}}</h1>
</div>
and its controller is this
function anonHomeController($scope) {
$scope.Title = " Welcome to Qiao";
$scope.qNavigationTemplatePath = "/templates/topMenu/anonTopNavigation.html";
$scope.copyrightMessage = "Qiao ";
$scope.copyrightYear = new Date();
};
The Question: How do I get Angular to recognise and use the partial template's controller?
While defining a controller, don't use any directory paths.
From the docs - https://docs.angularjs.org/api/ngRoute/provider/$routeProvider
controller – {(string|Function)=} – Controller fn that should be associated with newly created scope or the name of a registered controller if passed as a string.
Note that the registered controller never has the entire path, it is the function definition itself or the function's name (a string). You may need module names, if you have exported like that, but that's different from a directory path.
All you need is just use <script> tags in index.html, which will include all your functions. Now if your functions are just plain javascript, and you don't intend using angular.module('app').controller there, use it in the app.js, Just angular.module('app').controller('anonHomeController', anonHomeController); Note that your definition can still remain in the Javascript file /some/path/totemplate/anonHomeController.js. I suggest you try that and see if it works.
app.js
app.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when("/", {
templateUrl: 'templates/main/main.html',
controller: 'MainCtrl'
})
index.html
<script src="controllers.js"></script>
controllers.js
function MainCtrl ($scope) {
$scope.name = 'World';
}
A working plnkr here
You have created your controller for each view as a regular JS function, which is incorrect. It should be like
app.controller("anonHomeController", function ($scope) {
$scope.Title = " Welcome to Qiao";
// rest of the controller code
});
and the file should be anonHomeController.js at the path you have defined in the config. you also do not need to include the scipt tag in the header of the view. Check for some example here
You don't need to add complete path in your app.js for defining controllers.
If you're controllers are defined in the same file, then this should do the job:
$routeProvider
.when("/", {
templateUrl: 'templates/anonHome/anonHome.html',
controller: 'xyzController'
});
app.controller("xyzController", function ($scope) {
// controller function here
});
If you want your controllers to be in an external file, you'll have to do the following:
1. Define the controllers module:
angular.module('app.controllers', [])
.controller("homeController", function(){....})
Name this file as controllers.js
2. Now your main app.js should include this:
angular.module('app', [
'app.controllers',
])
Include controllers.js in your main html file

"win-list-view" element break page in Universal windows 8.1 project with WinJS and Angular

I try simple Universal windows 8.1 project.
My default.html page:
<!DOCTYPE html>
<html ng-app="mainApp">
<head>
<meta charset="utf-8" />
<!-- WinJS references -->
<script src="scripts/services/winstore-jscompat.js"></script>
<script src="node_modules/jquery/dist/jquery.min.js"></script>
<script src="node_modules/winjs/js/base.min.js"></script>
<script src="node_modules/winjs/js/ui.min.js"></script>
<!-- angular -->
<script src="node_modules/angular/angular.min.js"></script>
<script src="node_modules/angular-route/angular-route.min.js"></script>
<script src="node_modules/angular-winjs/js/angular-winjs.js"></script>
<script src="scripts/app.js"></script>
<script src="scripts/controllers/EventsController.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
Project has one simple view and simple controller. When I use "win-list-view" in my view, (even empty win-list-view without bounding) I got error which i do not understand.
HTML1300: Navigation occurred.
default.html
DOM7011: The code on this page disabled back and forward caching. For more information, see: http://go.microsoft.com/fwlink/?LinkID=291337
default.html
Error: [$compile:noslot] http://errors.angularjs.org/1.5.3/$compile/noslot? p0=true&p1=%3Cdiv%20class%3D%22ng-isolate-scope%22%20item-data- source%3D%22manufacturers%22%20ng-transclude%3D%22true%22%3E
...
My page is open, but data on screen are in json format. Whole data binding array is shown on screen.
View:
<div>
<win-list-view item-data-source="manufacturers">
<win-item-template>
<div>
<h4>{{item.data.title}}</h4>
<h6>{{item.data.text}}</h6>
</div>
</win-item-template>
<win-list-layout></win-list-layout>
</win-list-view>
</div>
Controller:
(function () {
angular.module("mainApp")
.controller("EventsController", function ($scope) {
$scope.manufacturers = [
{ title: "marvelous mint", text: "gelato" },
{ title: "succulent strawberry", text: "sorbet" },
];
})
}());
My app:
(function() {
angular.module("mainApp", ["ngRoute", "winjs"]);
angular.module("mainApp")
.config(function ($routeProvider) {
$routeProvider
.when("/events", {
templateUrl: "views/events.html",
controller: "EventsController"
})
.otherwise({ redirectTo: "/events" });
});
}());
Why "win-list-view" tag on view caused that error?
Work on windows 8 with VS2015, maybe it has influence.

Error: [$rootScope:infdig] http://errors.angularjs.org/1.4.1/$rootScope

I have the error below on my app
Error: [$rootScope:infdig] http://errors.angularjs.org/1.4.1/$rootScope/infdig?p0=10&p1=%5B%5D
at m.prototype.$digest (https://localhost:44301/angular.min.js:132:501)
at m.prototype.$apply (https://localhost:44301/Scripts/angular.min.js:135:159)
at Anonymous function (https://localhost:44301/Scripts/angular.min.js:19:315)
at e (https://localhost:44301/Scripts/angular.min.js:39:10)
at d (https://localhost:44301/Scripts/angular.min.js:19:236)
at zc (https://localhost:44301/Scripts/angular.min.js:20:23)
at Yd (https://localhost:44301/Scripts/angular.min.js:18:342)
at Anonymous function (https://localhost:44301/Scripts/angular.min.js:289:159)
at j (https://localhost:44301/js/jquery/jquery-2.1.1.min.js:2:26852)
at k.fireWith (https://localhost:44301/js/jquery/jquery-2.1.1.min.js:2:27609)
its only throw once when the app starts, and after I login to my active directory the app works fine across all views.
My app.js is like this:
(function () {
angular.module('inspinia', [
'ui.router', // Routing
'oc.lazyLoad', // ocLazyLoad
'ui.bootstrap', // Ui Bootstrap
'pascalprecht.translate', // Angular Translate
'ngIdle', // Idle timer
'AdalAngular', // ADAL JS Angular
'ngRoute' // Routing
])
})();
and part of my config.js
function config($stateProvider, $urlRouterProvider, $ocLazyLoadProvider, IdleProvider, KeepaliveProvider, adalAuthenticationServiceProvider, $httpProvider) {
// Configure Idle settings
IdleProvider.idle(5); // in seconds
IdleProvider.timeout(120); // in seconds
$urlRouterProvider.otherwise("/dashboards/dashboard_1");
$ocLazyLoadProvider.config({
// Set to true if you want to see what and when is dynamically loaded
debug: true
});
$stateProvider
.state('dashboards', {
abstract: true,
url: "/dashboards",
templateUrl: "views/common/content.html",
})
.state('dashboards.dashboard_1', {
url: "/dashboard_1",
templateUrl: "views/dashboard_1.html",
requireADLogin: true,
resolve: {
loadPlugin: function ($ocLazyLoad) {
return $ocLazyLoad.load([
{
serie: true,
name: 'angular-flot',
files: ['js/plugins/flot/jquery.flot.js', 'js/plugins/flot/jquery.flot.time.js', 'js/plugins/flot/jquery.flot.tooltip.min.js', 'js/plugins/flot/jquery.flot.spline.js', 'js/plugins/flot/jquery.flot.resize.js', 'js/plugins/flot/jquery.flot.pie.js', 'js/plugins/flot/curvedLines.js', 'js/plugins/flot/angular-flot.js', ]
},
{
name: 'angles',
files: ['js/plugins/chartJs/angles.js', 'js/plugins/chartJs/Chart.min.js']
},
{
name: 'angular-peity',
files: ['js/plugins/peity/jquery.peity.min.js', 'js/plugins/peity/angular-peity.js']
}
]);
}
}
})
adalAuthenticationServiceProvider.init(
{instance: 'https://login.microsoftonline.com/',
tenant: 'mysaasapp.onmicrosoft.com',
clientId: '33e037a7-b1aa-42ab-9693-6c22d01ca338',
extraQueryParameter: 'nux=1'
//cacheLocation: 'localStorage', // enable this for IE, as sessionStorage does not work for localhost.
},
$httpProvider
);
}
angular
.module('inspinia')
.config(config)
.run(function ($rootScope, $state) {
$rootScope.$state = $state;
});
My index.html
<!--
* INSPINIA - Responsive Admin Theme
* Version 2.0
*
-->
<!DOCTYPE html>
<html ng-app="inspinia">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Page title set in pageTitle directive -->
<title page-title></title>
<!-- Font awesome -->
<link href="font-awesome/css/font-awesome.css" rel="stylesheet">
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Main Inspinia CSS files -->
<link href="css/animate.css" rel="stylesheet">
<link id="loadBefore" href="css/style.css" rel="stylesheet">
</head>
<!-- ControllerAs syntax -->
<!-- Main controller with serveral data used in Inspinia theme on diferent view -->
<body ng-controller="MainCtrl as main">
<!-- Main view -->
<div ui-view></div>
<!-- jQuery and Bootstrap -->
<script src="js/jquery/jquery-2.1.1.min.js"></script>
<script src="js/plugins/jquery-ui/jquery-ui.js"></script>
<script src="js/bootstrap/bootstrap.min.js"></script>
<!-- MetsiMenu -->
<script src="js/plugins/metisMenu/jquery.metisMenu.js"></script>
<!-- SlimScroll -->
<script src="js/plugins/slimscroll/jquery.slimscroll.min.js"></script>
<!-- Peace JS -->
<script src="js/plugins/pace/pace.min.js"></script>
<!-- Custom and plugin javascript -->
<script src="js/inspinia.js"></script>
<!-- Main Angular scripts-->
<script src="Scripts/angular.min.js"></script>
<script src="js/plugins/oclazyload/dist/ocLazyLoad.min.js"></script>
<script src="js/angular-translate/angular-translate.min.js"></script>
<script src="js/ui-router/angular-ui-router.min.js"></script>
<script src="https://code.angularjs.org/1.2.25/angular-route.js"></script>
<script src="js/bootstrap/ui-bootstrap-tpls-0.12.0.min.js"></script>
<script src="js/plugins/angular-idle/angular-idle.js"></script>
<!--
You need to include this script on any page that has a Google Map.
When using Google Maps on your own site you MUST signup for your own API key at:
https://developers.google.com/maps/documentation/javascript/tutorial#api_key
After your sign up replace the key in the URL below..
-->
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDQTpXj82d8UpCi97wzo_nKXL7nYrd4G70"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="js/adal/adal.min.js"></script>
<script src="js/adal/adal-angular.js"></script>
<!-- Anglar App Script -->
<script src="js/app.js"></script>
<script src="js/config.js"></script>
<script src="js/translations.js"></script>
<script src="js/directives.js"></script>
<script src="js/controllers.js"></script>
</body>
</html>
and my content.html
<!-- Wrapper-->
<div id="wrapper">
<!-- Navigation -->
<div ng-include="'views/common/navigation.html'"></div>
<!-- Page wraper -->
<!-- ng-class with current state name give you the ability to extended customization your view -->
<div id="page-wrapper" class="gray-bg {{$state.current.name}}">
<!-- Page wrapper -->
<div ng-include="'views/common/topnavbar.html'"></div>
<!-- Main view -->
<div ui-view></div>
<!-- Footer -->
<div ng-include="'views/common/footer.html'"></div>
</div>
<!-- End page wrapper-->
<!-- Right Sidebar -->
<div ng-include="'views/common/right_sidebar.html'"></div>
</div>
<!-- End wrapper-->
I was able to filter down the issue to something with ADAL.JS
If I remove the requireadlogin line and the .init lines to configure authentication, the error is gone.
.run(function ($rootScope, $state) {
$rootScope.$state = $state;
});
The error is happening when you try to increase the $rootScope.
The error is indicating that he is entering a very large loop and the angular own for security abort your request.
If you wanna add two or more values into a rootscope, why you do not try to use .push function and save all the data into a array?

AngularJS templates not loading/rendering

So I'm trying to run an Angular app with a Rails API on Chrome.
I'm trying to render very simple views from their respective controllers.
My users.js controller:
'use strict';
var rantlyApp = angular.module('rantlyApp', ['ngRoute']);
rantlyApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/users', {
templateUrl: '/views/users.html',
controller: 'UsersCtrl'
});
}])
.controller('UsersCtrl', ['$scope', '$http', function ($scope, $http) {
$http.get('http://localhost:3000/api/users/').success(function(data) {
$scope.users = data.users;
});
$scope.foos = ['foo', 'bar', 'baz'];
}]);
users.html view:
<div ng-controller='UsersCtrl'>
<h1>Users</h1>
<ul ng-repeat="user in users">
<li>{{user.first_name}}</li>
</ul>
<ul ng-repeat="foo in foos">
<li>{{foo}}</li>
</ul>
</div>
The users page renders fine, and I get all the data I want. But when I try to load my main page, I get nothing. No errors, just a blank screen (though the navbar and everything else I have in my index.html loads properly).
My main.js controller:
'use strict';
var rantlyApp = angular.module('rantlyApp', ['ngRoute']);
rantlyApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: '/views/main.html',
controller: 'MainCtrl'
});
}])
.controller('MainCtrl', ['$scope', function ($scope) {
$scope.awesomeThings = [
'foo',
'bar',
'baz'
];
$scope.addThing = function() {
$scope.awesomeThings.push($scope.newThing);
$scope.newThing = '';
};
}]);
main.html view:
<div ng-controller="MainCtrl">
<form ng-submit='addThing()'>
<div class="form-horizontal">
<input type="text" ng-model="newThing">
<input type="submit" value="Add Thing">
</div>
</form>
<li ng-repeat='thing in awesomeThings'>
{{thing}}
</li>
<h4>Awesome things: {{awesomeThings}}</h4>
<h4>Cool things: {{coolThings}}</h4>
</div>
When I look at the inspector in the Network tab for the "/users" route, it loads users.html. This doesn't happen for the "/" route. I expect it to load main.html, but I get nothing.
The strange thing is, when I copy all of my code from my main.js and just throw it into my users.js, everything works fine. This told me maybe I wasn't loading it properly into the index.html page, but it seems to me that I am.
index.html:
(scripts are at the bottom)
<!doctype html>
<html class="no-js">
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="styles/main.css">
</head>
<body ng-app="rantlyApp">
<header class='nav-header' role='navigation'>
<div class='content'>
<a class="navbar-brand" href="#/">Rantly</a>
<nav>
Rants
Users
Styleguide
Sign Up
</nav>
</div>
</header>
<div class="container">
<div ng-view=""></div>
</div>
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID -->
<script>
!function(A,n,g,u,l,a,r){A.GoogleAnalyticsObject=l,A[l]=A[l]||function(){
(A[l].q=A[l].q||[]).push(arguments)},A[l].l=+new Date,a=n.createElement(g),
r=n.getElementsByTagName(g)[0],a.src=u,r.parentNode.insertBefore(a,r)
}(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXX-X');
ga('send', 'pageview');
</script>
<script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>
<script src="bower_components/angular-animate/angular-animate.js"></script>
<script src="bower_components/angular-cookies/angular-cookies.js"></script>
<script src="bower_components/angular-resource/angular-resource.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="bower_components/angular-sanitize/angular-sanitize.js"></script>
<script src="bower_components/angular-touch/angular-touch.js"></script>
<!-- endbower -->
<!-- endbuild -->
<!-- build:js({.tmp,app}) scripts/scripts.js -->
<script src="scripts/app.js"></script>
<script src="scripts/services.js"></script>
<script src="scripts/controllers/main.js"></script>
<script src="scripts/controllers/users.js"></script>
<script src="scripts/controllers/about.js"></script>
</body>
</html>
I'm extremely new to Angular so it's quite possible I'm missing a fundamental step in setting up the controllers. Since my code works based purely off of which file I have it in, I have a feeling I'm not configuring something properly in Angular.
Any help is greatly appreciated. Thanks!
When you write
var rantlyApp = angular.module('rantlyApp', ['ngRoute']);
You are creating a new module called rantlyApp and removing any old module with the same name. So when the users.js script runs it overwrites what you defined in main.js.
Instead define your module once, and retrieve it with:
var rantlyApp = angular.module('rantlyApp');
Check the documentation.

Categories