Angularjs routing not working - angularjs

Everything worked fine until I tried to add routing. I read that Angularjs version 1.2+ requires 'ngRoute' as an dependency (I am using version 1.2.16). I added it but it still doesn't work. Below are my codes.
test.html (Main Page)
<html ng-app="demoApp">
<head>
<title></title>
</head>
<body>
<p>Front Page</p>
<div ng-view></div>
<script src="angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-route.js"></script>
<script src="testjs.js"></script>
</body>
</html>
testjs.js
demoApp = angular.module('demoApp',['ngRoute']);
demoApp.config(function ($routeProvider) {
$routeProvider.when('/', {
controller: 'SimpleController',
templateUrl: '/partials/first.html'
});
});
var controllers = {};
controllers.SimpleController = function ($scope){
$scope.first = "Info";
$scope.customers=[
{name:'jerry',city:'chicago'},
{name:'tom',city:'houston'},
{name:'enslo',city:'taipei'}
];
};
demoApp.controller(controllers);
first.html
<div>
<input type="text" ng-model="name"/>
</br>
{{first}}
</br>
<ul>
<li ng-repeat="cust in customers | filter:name">{{cust.name | uppercase}} - {{cust.city}}</li>
</ul>
</div>

Here is the most basic setup possble, I'll try to make another one with your code:
http://plnkr.co/edit/sN9TagVBOdX3mkrxaTiu?p=preview
EDIT updated with the sample code. Everything seems to be working?
EDIT 2 the problem is OP wasn't running a webserver. Ng-Route needs a webserver to function properly.

My routing wasn't working because there was an exclamation point inserted in the url when I tried to navigate to my routes. I added $locationProvider like this
app.config(function($routeProvider, $locationProvider) {
$locationProvider.hashPrefix('');
to remove the exclamation point and my template views started appearing when I navigated to them. I found the answer here Exclamation mark after hash (#!) in angularjs app

Related

angularjs routing tutorial bug not routing

I just created a simple project to learn angular routing, my project is the following:
index.html:
<!DOCTYPE html>
<html ng-app="app">
<body>
<div>
Home
Hi
bye
</div>
<div class="ng-view"></div>
<script src="https://code.angularjs.org/1.6.3/angular.min.js"></script>
<script src="https://code.angularjs.org/1.6.3/angular-route.min.js"></script>
<script src="scripts.js"></script>
</body>
</html>
scripts.js:
var app = angular.module("app", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "home.html"
})
.when("/hi", {
templateUrl: "hi.html"
})
.when("/bye", {
templateUrl: "bye.html"
});
});
hi.html: <h1>Hi</h1>
bye.html: <h1>bye</h1>
home.html: <h1>Home</h1>
The three html from above only contains a h1 tag to keep it simple
A plunker of my code: http://plnkr.co/edit/uNZicTuRKDkR7ATwdFE0
I'm following this tutorial: https://www.w3schools.com/angular/angular_routing.asp
Dunno if outdated or why its not working, thanks
The problem is that you are using angular 1.6 and the toturial is using 1.4. Your links should be like this because of the new hash prefix in version 1.6:
<div>
<a ng-href="#!/">Home</a>
<a ng-href="#!/hi">Hi</a>
<a ng-href="#!/bye">bye</a>
</div>
See plunker.
http://plnkr.co/edit/qUYYcFjfwi9kEGxa7zOu?p=preview
Read more about what else to do at: https://stackoverflow.com/a/41655831/6682369

Why does this code break once "app" and the ng-controller are added?

This code is virtually verbatim from egghead.io, but it is not working at all unless I remove ="app" and remove the ng-controller attribute from the <body> element. (And of course the last <script> element gets ignored in the process—the code that would normally be in app.js.) Of course removing those bits prevents anything else from working or being added.
<!doctype html>
<html ng-app="app">
<head>
<script src="http://code.angularjs.org/angular-1.0.0.min.js"></script>
<script src="http://code.angularjs.org/angular-ui-router-1.0.0.min.js"></script>
<script>
angular.module('app', ['ui.router'])
.controller("FirstCtrl", function FirstCtrl() {
var first = this;
first.greeting = "First";
});
</script>
</head>
<body ng-controller="FirstCtrl as first">
<div>
<input type="text" ng-model="first.greeting" placeholder="First Name">
<hr>
<h1>{{ first.greeting }} World!</h1>
</div>
</body>
</html>
Here's similar code on JSFiddle. (It's only similar because JSFiddle imposes constraints that make it impossible to post identical code. It has the same problem, so I assume the differences are insignificant for tracking down the source of the bug.)
Where is the bug? Why is this not working?
With latest angular dependency it worked for me.
<!doctype html>
<html ng-app="app">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
<script>
angular.module('app', ['ui.router'])
.controller("FirstCtrl", function FirstCtrl() {
var first = this;
first.greeting = "First";
});
</script>
</head>
<body ng-controller="FirstCtrl as first">
<div>
<input type="text" ng-model="first.greeting" placeholder="First Name">
<hr>
<h1>{{ first.greeting }} World!</h1>
</div>
</body>
</html>
You are using angular ui-router but not using it the way you are supposed to be. Check the documentation here to get a clearer idea. Angular UI router loads its contents in a container containing ui-view attribute. As per documentation
AngularUI Router is a routing framework for AngularJS, which allows you to organize the parts of your interface into a state machine. Unlike the $route service in Angular core, which is organized around URL routes, UI-Router is organized around states, which may optionally have routes, as well as other behavior, attached.
You need to load different states in your ui-view and also pass values in different states in the process. You need to add dependencies for $stateProvider and $urlRouterProvider in your app config for a completely functional angular ui router implementation. This being told what you need to do is like below -
And also check out the working example in PLUNKER
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<title>AngularJS: UI-Router Quick Start</title>
<!-- Bootstrap CSS -->
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="container">
<div class="row">
<div class="span12">
<div class="well" ui-view></div>
</div>
</div>
<!-- Angular -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.js"></script>
<!-- UI-Router -->
<script src="//angular-ui.github.io/ui-router/release/angular-ui-router.js"></script>
<!-- App Script -->
<script>
var myapp = angular.module('myapp', ["ui.router"])
myapp.config(function($stateProvider, $urlRouterProvider){
// For any unmatched url, send to /route1
$urlRouterProvider.otherwise("/route1")
$stateProvider
.state('route1', {
url: "/route1",
templateUrl: "route1.html",
controller: function($scope) {
$scope.greeting = "First";
}
})
})
</script>
</body>
</html>

AngularJS - routing doesn't work

I am learning angular js for a project i'm building.
So far it seems like a great framework, very helpful and intuitive,
but i am having problems whenever i try to implement routing...
I have this code:
<!DOCTYPE html>
<html data-ng-app="myApp">
<head>
<title></title>
<meta charset="utf-8" />
<script src="libs/angular.min.js"></script>
<script src="libs/angular-route.min.js"></script>
<script type="text/javascript">
var app = angular.module('myApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'home.html',
controller: 'HomeController'
}).otherwise({ redirectTo: '/' });
});
app.controller('HomeController', function ($scope) {
$scope.people = [
{
name: "Arik",
age: 19
},
{
name: "Bar",
age: 19
}
];
});
</script>
</head>
<body>
<div data-ng-view></div>
</body>
</html>
and home.html:
<ul>
<li data-ng-repeat="person in people">
<b>{{ person.name }}</b> - {{ person.age }}
</li>
</ul>
The problem is that it just doesn't work, the page shows blank.
I tried searching in the official documentation but nothing helped...
What am i doing wrong?
By the way, i am using the latest version, 1.4.4
Thanks,
Arik
I just tested your code here and works fine, probably the issue is in your path to home.html or your web server or something similar, look at your environment.
Try out grunt-connect to create a web server while you are developing, it's very helpful
Also i recommend you to use ui-router, is much more simple. Here is a working template for routing with ui-router in plunker
Your code looks great, and the prove is that it works take a look at this,
I would recommend you to load the scripts after the html, so you don't keep the user looking at a blank page till the file is downloaded.

AngularJS and Angular-Route-Segment

I am new to AngularJS so any tips will be welcome as I'm still trying to wrap my head around how everything works.
The following controller houses other controllers inside of it, however I've shortened the code to replicate my problem without the inner segments (I'll have more bugs once I add that in).
This is my html section:
<div ng-app="app">
<div class="ng-cloak" ng-controller="mainController">
<a ng-class="{active: ('sectionHome' | routeSegmentStartsWith)}" href="#{{'sectionHome' | routeSegmentUrl}}">Home</a>
<div id="content" style="">
<div app-view-segment="0"></div>
</div>
<div id=loading class=alert ng-show="loader.show">Loading...</div>
</div>
</div>
And the javascript:
var app = angular.module('app', ['ngRoute', 'ngAnimate', 'route-segment', 'view-segment']);
app.config(function($routeSegmentProvider, $routeProvider) {
$routeSegmentProvider.options.autoLoadTemplates = true;
$routeSegmentProvider
.when('/Home', 'sectionHome')
.segment('sectionHome', {
'default': true,
templateUrl: '../templates/sHome.html',
controller: 'mainController'})
$routeProvider.otherwise({redirectTo: '/Home'});
}) ;
app.value('loader', {show: false});
app.controller('mainController', function($scope, $routeSegment, loader) {
$scope.$routeSegment = $routeSegment;
$scope.loader = loader;
$scope.$on('routeSegmentChange', function() {
loader.show = false;
})
});
I'm either missing something conceptual or some other big thing, since when I inspect the link it appears that the scope bindings are not set in the html document and I remain with "ng-class="{active: ('sectionHome' | routeSegment...".
I've tried editing the code in jsFiddle (http://jsfiddle.net/3boccdu6/) however there I'm receiving an error
"..[$injector:nomod] Module 'app' is not available! You either misspelled the module name or forgot to load it.."
This would make sense but I'm really not sure what I'm doing wrong, I've been following this working example:
http://angular-route-segment.com/src/example/#/section3
Adding the following to your html will resolve the issue.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular-resource.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular-route.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-route-segment/1.4.0/angular-route-segment.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular-animate.min.js">
</script>
<script src="app.js"></script>

Use ng-controller and $routeProvider at the same time

The issue is that I have an index page, whith a(some) partial(s) view(s) that we can call "A.html" with a controller "ACtrl" assigned by $routeProvider, but inside that partial view, I would like to use a different controller for some divs using ng-controller to include a "A1Ctrl".
Is this possible?
Not focus on any code, but in the concept if this is barely possible and how?
I tried to include in the partial view something like this with no success:
A.html
... //Other stuff for this partial view
<div ng-controller="A1Ctrl">
{{message}}
</div>
... //More stuff for this partial view
I have included the .js where the A1Ctrl is defined to the index page with same result. Any tip?
UPDATE:
I have create in plnkr a sample code to show what I want to do: http://plnkr.co/edit/hdpLMK3DbzNdz2KeHPEB?p=preview
I have partial view generated after clicking "Say hi" which has its own template ("first.html") and controller, injected by the $routeProvider. But in that partial view in first.html I want to add a which has its own controller for only that section of code. But I can't make it work, any suggestion?
I also tried to use Dependency Injection to include the module "multilinguage" into router.js with no success because it seems to generate an error.
index.html
<html ng-app="plunker">
<head>
... //Other imports
<script src="app.js"></script>
<script src="router.js"></script>
<script src="multilanguage.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
Say hi |
Say bye
<br/>
<div ng-view=""></div>
</body>
</html>
first.html
{{message}}
<div ng-controller="MultiLang">
{{message}}
</div>
router.js
var app = angular.module('router', ['ngRoute', 'multilanguage']).
config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.
when("/first", {
templateUrl: "first.html",
controller: "EngLang"
}).
when("/second", {
template: "Bye man!"
});
});
app.controller('EngLang', function($scope) {
$scope.message = 'Hi guys';
});
multilanguage.js
angular.module('multilanguage', []).
controller('MultiLang', function($scope){
$scope.message = "Hallo, Hola, Ciao, Ni Hao"
});
Thanks in advance.
Yes, also you can use nested controllers, for example:
<div ng-controller="A1Ctrl">
{{ message }}
<div ng-controller="subCtrl">
{{ message }}
</div>
</div>

Resources