Simple AngularJS Program is Blank in Browser - javascript

I'm working on learning some Angular for an application I'm building.
After going through some tutorials, I had a basic program working which had two views and some routing to flip between them. I'm running it now in the browser, and it's coming up blank. There are no console errors, and I swear I haven't touched it since I had it working last.
Here's my main file:
<!DOCTYPE html>
<html lang="en">
<head>
<title>AngularJS Routing example</title>
<style>
body
{
font-family: arial;
padding: 20px;
}
</style>
</head>
<body ng-app = "journal_program">
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src = "app.js"></script>
<div ng-view>
</div>
</body>
</html>
And my Javascript:
var journal_program = angular.module ("journal_program", []);
journal_program.config (['$routeProvider', function ($routeProvider)
{
$routeProvider.
when ('/AddNewOrder',
{
templateUrl: 'templates/add_order.html'
}).
when ('/ShowOrders',
{
templateUrl: 'templates/show_orders.html'
});
}]);
The first view:
<h2>Add New Order</h2>
Show Order
The second view:
<h2>Show Orders</h2>
Back<br>
Any ideas are appreciated. I'm not sure what to check at this point.
UPDATE:
Here are the 3 important things I figured out from this little exercise:
1) Angular views don't have a default route unless you set one with "otherwise". Basically, even if you've set up a couple different routes, ng-view is blank when the page first loads unless either the user loads a route by clicking a link outside the view, or if you've set a default by adding "otherwise" to your route controller.
otherwise (
{
templateUrl: 'templates/add_order.html'
});
This link is extremely helpful:
http://blog.kevinchisholm.com/angular/angular-js-basics-routes-part-iii-creating-a-default-route/
2) Apparently nothing you put inside the html of ng-view will be rendered unless you have a " when ('/' " route in the controller.
3) Angular doesn't work so well when run off the hard drive. You've got to upload it to a server first, for whatever reason.
After adding these steps I got my demo working again. Looking back now, I'm not sure how I got it working the first time around without this knowledge.

It working fine...
Take a look at this Demo
Working Demo
<div ng-view>
</div>
<h2>Show Orders</h2>
Show Order
<h2>Add New Order</h2>
Add Order
<br>

Related

Site pages not scrollable after adding angularjs

I have a site that was downloaded first as a template. in order to convert into an angular app, i removed all the <head>, <html> and <body> tags of all other pages except the index page which contains the <ng-view>. now the routing is working just fine to redirect to all the pages but the problem is that the pages are not scrolling anymore. the index.html page looks like this
<!DOCTYPE html>
<html lang="en" ng-app="myApp" ng-controller="IndexController">
<head>
<title>My site</title>
</head>
<body>
<div ng-view [onload="string"]
[autoscroll="string"]></div>
</body>
</html>
and the other pages look something like this
<div>
<!-- page content goes here-->
</div>
app config is like
var app = angular.module('myApp',['ngRoute','LocalStorageModule','ngStorage']);
app.config(
function($routeProvider)
{
$routeProvider
.when("/", {templateUrl : "home.html", controller: 'HomeController' })
//other routes
});
when i run this site, all the pages that have long content are cut short and cannot scroll to view the rest of the content. please help. I have been working with angularjs for some time now but i have never come across anything like this before.

Angular: A controller with this name is not registered

I've been trying to figure this out for a few hours now, and I can't seem to find the problem. I've read some other questions with similar problems, but they don't have any solutions that have worked for me.
I am having trouble registering my controllers. I am not able to register controllers outside of the file in which I declare the app. Originally, I set up the 'MainController' in a separate file, which failed. I was getting an error saying that "The controller with the name 'MainController' is not registered". Once I put MainController in the same file as the app is declared, there were no problems. However, when I have a lot of code, I don't want all the controllers in the same file, as it will become too difficult to read. Here are examples of my code:
angular.module('myApp', ['ngRoute']);
angular.module('myApp')
.controller('MainController', MainController);
I am keeping other controllers in different files, and they are not registering. For example, in home.controller.js:
angular.module('myApp')
.controller('HomeController', HomeController);
function HomeController(HomeService) {
}
This controller will not register, and I don't know why. Each HTML partial in ng-view has its own controller, and the ng-view is within the MainController. Here is the app.config.js file:
angular.module('myApp')
.config(function($routeProvider, $locationProvider) {
$routeProvider.when('/home', {
templateUrl: 'views/home.html',
controller: 'HomeController as home'
}).when('/profile', {
templateUrl: 'views/profile.html',
controller: 'ProfileController as profile'
});
$locationProvider.html5Mode(true);
});
Here is index.html:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<title>My App</title>
<script src="vendors/angular.min.js"></script>
<script src="vendors/angular-route.min.js"></script>
<script src="scripts/app.module.js"></script>
<script src="scripts/app.config.js"></script>
<scripts src="scripts/home.controller.js"></scripts>
<scripts src="scripts/profile.controller.js"></scripts>
<script src="scripts/main.service.js"></script>
<script src="scripts/home.service.js"></script>
<script src="scripts/profile.service.js"></script>
<base href="/" />
</head>
<body ng-controller="MainController as main">
<header>
<h1>My App</h1>
</header>
<!-- Content varies -->
<div class="container">
<ng-view></ng-view>
</div>
</body>
</html>
I have successfully built projects like this in the past without problem, but I can't find any issue compared to those projects. Any help is appreciated!
When I've had this issue in the past, it was related to script loading order, especially with using async script loading. You don't appear to be doing that.
To troubleshoot:
Fire a console log statement inside the controller's function body (console.log('registering controller x')). This statement will either not show up, or will show up after the error.
Angular used to (and I presume it still does) try to wait for app to load and all controllers to register to app before running the code. Either Angular isn't waiting on this controller, or this controller isn't running.
From there, you would verify that the reference to the file is correct (put a console.log at the top of the file), or determine how Angular decides when it believes all controllers are loaded and why it doesn't wait on your controller.
I haven't dealt with Angular since 1.2, because I think it's a pretty bad framework. But that was my experience then, and it seems like the same basic architecture for this. Back then it was relying on Document.ready. I really hope they don't do that anymore (that's where I ran into my async script loader problems).
Best of luck.

HTML avoid coping blocks of code

I trying to learn web technologies (HTML, JS, angular, etc. what is needed to create pages). For practice I downloaded some kind of website template and noticed that there is a lot of same code in different html files(pages).
For example we have pages: login,main,about. Each of this page has same <header/> and <footer> and difference is only in <section/> between them.
So is it possible to have such structure: Main page with header and footer and on menu click changes only section between them? It will look like single page app.
As I use angularjs I know that there is such attribute as a ng-view but I am not sure if it will be suitable here, when, lets call, inner pages have this attribute inside also. (I tried I got RangeError: Maximum call stack size exceeded not sure probably some kind of infinitive loop appeared).
So what would be best solution in particular situation, I am not sure that my suggested structure is good, but I do not want to have same blocks of code in each page or it should be in HTML?
I use HTML, angular, JS, bootsrap for theme.
Examle
I copied two pages as example to plunker, so As you can see a lot of code is same, so I want to show login.html inside index.html (line: 172), but in login.html I also have ng-view (line:177). Maybe someone can with small code sample can show me how it is made?
http://plnkr.co/edit/iJrg2FJgwr9xxKTWMouX?p=preview
Yes, it's possible with AngularJs, and in fact very easy using ng-view or ui-view (from ui-router) .
Depending on your level of expertise I would suggest taking a look at ui-router which has all the ng-router functionalities and even more.
You can use ui-router to achieve this. You can define your states and templates using ui-router. Then for each state you can inject your views into sections marked as ui-view in your templates. Check out the example.
var myApp = angular.module("myApp", ["ui.router"]);
myApp.config(function($stateProvider) {
$stateProvider
.state('main', {
url: '/',
template: 'Main Page'
})
.state('list1', {
url: 'list1',
template: '<div>List1 {{test}}</div>',
controller: function($scope) {
$scope.test = "List 1";
}
})
.state('list2', {
url: 'list2',
template: '<div>List2 {{test}}</div>',
controller: function($scope) {
$scope.test = "List 2";
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
<html ng-app="myApp">
<body>
<div><a ui-sref="main">Header</a> <a ui-sref="list1">List1</a> <a ui-sref="list2">List2</a>
</div>
<div ui-view=""></div>
<div>Footer</div>
</body>
</html>
A simple routing setup for an app using ngRoute would be something like this.
angular.module('stack-app', ['ngRoute']);
// set up the views at configure time
angular.module('stack-app').configure(['$routeProvider',
function($routeProvider) {
$routeProvider.when('/view1', { // http://website.com/view1
controller: 'View1Controller', // the controller for view1
templateUrl: 'view1.html' // this is a partial view
});
$routeProvider.when('/view2', { // http://website.com/view2
controller: 'View2Controller', // controller for view 2
template: '<div>inline template should do just fine</div>'
});
$routeProvider.otherwise('/view1'); // http://website.com/anythingelse points to /view1
}
]);
angular.module('stack-app').controller('StackMainController', function() {});
angular.module('stack-app').controller('View1Controller', function() {});
angular.module('stack-app').controller('View2Controller', function() {});
index.html here you would put the common parts, headers etc.
<html ng-app="stack-app">
<body ng-controller="StackMainController">
<!-- this will be replaced by the partial views -->
<ng-view></ng-view>
</body>
</html>
You will have to configure whatever server you are using to serve index.html when receiving requests for /view1 or /view2.
Also don't forget to import the angular-route.js file in your project.
You can also have other modules register routes in their own configure method, there's no need to have a central config.

AngularJS - importing controllers inside controllers

I have diferents controllers in my webpage, each controller is in a different .php document. Each .php document represents a diferent part of the webpage. (It's similar to spotify).
player.php: (Where the user can play some music with an audio player)
<html ng-app="decibels-interactive" lang="en">
<body ng-controller="InteractiveController as interactCtrl">
panel_admin.php: (where the user can modify its data and some data of the webpage)
<html lang="en" ng-app="decibels-admin">
<body ng-controller="AdminController as AdminCtrl" ng-init="AdminCtrl.sessionCtrl()">
player.php and panel_admin.php have its respective player.js and panel_admin.js with its .controllers running correctly.
player.js:
var decibelsInteractive = angular.module("decibels-interactive", []);
decibelsInteractive.controller('InteractiveController', function ($scope, $log) {
panel_admin.js:
var adminControl = angular.module("decibels-admin", []);
adminControl.controller("AdminController", function($scope){
Now, I have the menu bar in menu.php, where I use in player.php document, imported with:
//player.php
<html ng-app="decibels-interactive" lang="en">
<body ng-controller="InteractiveController as interactCtrl">
<?php include('includes/menu.php'); ?>
//here some html code
</body>
</html>
menu.php: (menu is a menu bar where the user have some options, and it also have its username and logout option)
<div class="navbar-fixed" ng-controller="InteractiveController as menu2">
//some html code
</div>
menu.js:
app.controller('menu2', function($scope) {
$scope.content = '';
});
The problem that I have is that as you can see, I import the document menu.php inside player.php.
I also want to import the menu.php inside panel_admin.php and be able to use some methods that I have in menu.js, so the code that I have in menu.php (ng-controller="") is not correct (or I think so). -Because when I use it in panel_admin.php it will be in conflict with ng-controller name.
Someone told me that I should use services, or that I should define menu in separate module and use it as dependency where I want.
I am new with angularJS so now I'm a little lost. I've been searching information about services and dependencies without success.
I hope to solve this problem and being able to continue programming!
Thank you!

AngularJS multiple ngApps each with its own ngRoute definitions, lazyloaded and bootstrapped on one page

My question comes from the need to lazy load different/separate ngApps on one page(bootstrapping them with angular.bootstrap), each of them using its own ngRoute definitions(defined in such a way that they do not overlap each other).
Now I have a working plunkr example and all seems to function well, but somehow I have the feeling that this is not the correct approach so that's why Im asking here for advice.
<!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<div class="container">
<div class="col-xs-6 well" id="app1">
<h3>App1</h3>
Route 1
Route 2
Route 3
<div class="well" ng-view></div>
</div>
<div class="col-xs-6 well" id="app2">
<h3>App2</h3>
Route 1
Route 2
Route 3
<div class="well" ng-view></div>
</div>
</div>
<script type="text/javascript" src="https://code.angularjs.org/1.2.21/angular.min.js"></script>
<script type="text/javascript" src="https://code.angularjs.org/1.2.21/angular-route.min.js"></script>
<script>
var app1 = angular.module('app1', ['ngRoute']);
app1
.config(function($routeProvider) {
$routeProvider
.when('/:app/:param', {
template: 'app = {{app}}, param = {{param}}',
controller: 'Ctrl1'
})
})
.controller("Ctrl1",['$scope','$routeParams', function($scope,$routeParams) {
$scope.app = $routeParams.app;
$scope.param = $routeParams.param;
}]);
var app2 = angular.module('app2', ['ngRoute']);
app2
.config(function($routeProvider) {
$routeProvider
.when('/:app/:param', {
template: 'app = {{app}}, param = {{param}}',
controller: 'Ctrl2'
})
})
.controller("Ctrl2", ['$scope','$routeParams', function($scope,$routeParams) {
$scope.app = $routeParams.app;
$scope.param = $routeParams.param;
}]);
angular.bootstrap(document.getElementById("app1"), ['app1']);
angular.bootstrap(document.getElementById("app2"), ['app2']);
</script>
</body>
</html>
http://plnkr.co/edit/Y7A9bc3bDUyAXIS13JMZ?p=preview
FYI: I have already checked out ui-router to load separate states on one page, but it all requires for the source code to be loaded upfront(and have a single app.config with all routes in it) which is something I do not want as the Project is quite huge. So for the sake of keeping it simple and modular Im looking for something like the above example.
UPDATE to answer HockeyJ question:
OK I will try to keep this as short as possible. Very basically put - as I said the project could potentially become quite huge, from source code and module dependency perspective. This is why I want to make it in such a way, that each module can be totally separate App, able to be injected at any place and tested separately(thats not really an issue with AnJS). In the same time however the whole project, should be a single page app. As such there should not be screen reloads(to load an App jscript files) etc. Hence comes the lazy loading of scripts on demand and bootstrapping apps to DOM elems. The only possible intersection point of all apps is the URL routing which has strict naming convention for routes i.e. /reports/whatever ; /transactions/whatever etc. and should be managed by ngRoute.
UPDATED:
Checkout overmind project for angular and the demo here
Shows a project broken up into several apps: nav, home, profile, and admin. The nav app is always on the page and is the only app bootstrapped on pageload.
Just take routing out of angular and use something like sammy.js , history.js etc for client side routing.
Use
angular.bootstrap(module, node)
in the routes of your sammy handlers
Also you might want to take a look at react.js (with or without flux) and tide it up with sammy the same way. Consider this example from todombc : https://github.com/tastejs/todomvc/tree/gh-pages/architecture-examples/react

Categories