AngularJs routing is failing - angularjs

My Index.html
<!doctype html>
<html data-ng-app="hotelApp">
<head>
<title>SRK Hotel</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- <link rel="stylesheet" href="stylesheets/style.css"> -->
<!-- Angular dependencies -->
<link rel="stylesheet" type="text/css" href="lib/angular-material/angular-material.css">
<script src="lib/angular/angular.min.js"></script>
<script src="lib/angular-animate/angular-animate.min.js"></script>
<script src="lib/angular-aria/angular-aria.min.js"></script>
<script src="lib/angular-material/angular-material.min.js"></script>
<script src="lib/angular-ui-router/release/angular-ui-router.min.js"></script>
<script src="scripts/start.js" type="text/javascript"></script>
<script src="scripts/home-page-ctrl.js" type="text/javascript"></script>
<script src="scripts/states/misc-states.js" type="text/javascript"></script>
</head>
<body>
<!-- <div data-ng-include="'views/welcome-page.html'"></div> -->
<div ui-view="welcome"></div>
</body>
</html>
My app.js
(function() {
angular.module('hotelApp.controller', []);
angular.module('hotelApp.states', ['ui.router']);
angular.module('hotelApp', ['ui.router']);
})();
My states.js - that is there for declaration of states
angular.module('hotelApp.states')
.config(function ($stateProvider, $urlRouterProvider) {
'use strict';
$stateProvider
.state('hotelApp.homePage', {
url: '/home',
views: {
'welcome': {
templateUrl: 'views/welcome-page.html',
conntroller: 'homePageCtrl'
}
}
});
$urlRouterProvider.when('/', function($state){
console.log('$state ' , $state);
$state.go('hotelApp.homePage');
});
$urlRouterProvider.otherwise(function(){
console.log('hi');
});
});
my nodejs file
var express = require('express');
var cfenv = require('cfenv');
var app = express();
app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/public/views'));
app.use('/lib', express.static(__dirname + '/node_modules'));
app.get('*', function(req, res) {
res.sendFile(__dirname+'/public/index.html');
});
var appEnv = cfenv.getAppEnv();
app.listen(appEnv.port, '0.0.0.0', function() {
console.log("server starting on " + appEnv.url);
});
I am trying to use routing in this implementation but it is failing.
I have added this code but when i run my code.. nothing happens .. I just get a blank page. What is wrong with this implementation.? I get no error, no logs.

Your main module is defined as
angular.module('hotelApp', ['ui.router']);
So it depends exclusively on ui-router.
Your states are defined in a separate module, 'hotelApp.states', which is thus not part of your application.
Another problem is that the two JS files you've posted are app.js and states.js, and there is no <script> element in your html page for those two files. So the're not even loaded by the browser.

Related

AngularJS controller won't load into partial

I'm trying to create a login/signup site in order to learn how to separate controllers and partial views, but I'm not sure why my 'LoginController' isn't being injected. Feel free to provide any other feedback.
app.js
angular.module('Registration', ['ngRoute'])
.config(['$routeProvider', ($routeProvider) => {
$routeProvider
.when('/login', {
templateUrl: 'app/login/login.html',
controller: 'LoginController'
})
.otherwise({ redirectTo: '/login' });
}]);
LoginController.js
angular.module('Registration')
.controller('LoginController', ['$scope', ($scope) => {
$scope.message = 'Does this work?';
}]);
login.html
<div class="col-md-offset-3 col-md-6">
{{ message }}
</div>
index.html
<!doctype html>
<html ng-app="Registration">
<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>Sup?</title>
<link rel="stylesheet" type="text/css" href="assets/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="assets/css/styles.css">
</head>
<body>
<div class="container">
<div class="row">
<div ng-view></div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script src="assets/js/angular.min.js"></script>
<script src="assets/js/angular-route.min.js"></script>
<script src="app/app.js"></script>
<script src="app/login/LoginController.js"></script>
</body>
</html>
server.js
var express = require('express');
var app = express();
app.use(express.static('./public'));
app.listen(3000, () => {
console.log('Listening on port 3000.');
});
Directory Structure
Turns out you can't use an arrow function in the controller! Totally didn't mean to answer my own question.
Found the answer here: https://github.com/angular/angular.js/issues/14814
Just try to reach to your login route like http://localhost:8080/#/login

Ionic controllers and services

I'm pretty new with Ionic and AngularJS. I tried to create an app but it seems that the content of app.js is wrong .
This is my code look like :
app.js
angular.module('starter', ['ionic', 'starter.controllers'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider.state('app', {
url: "/ListeUsers",
views: {
templateUrl: "templates/ListeUsers.html",
controller: 'UsersCtrl'
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/ListeUsers');
});
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ionic/js/angular/angular-resource.min.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/UserControllerIonic.js"></script>
<script src="js/UsersServiceIonic.js"></script>
</head>
<body ng-app="starter">
<ion-nav-view></ion-nav-view>
</body>
</html>
userControllerIonic.js
angular.module('starter.controllers', ['starter.services'])
.controller('UsersCtrl', function($scope,userService) {
$scope.Users=userService.getUsers();
});
UsersServiceIonic.js
angular.module('starter.services', ['ngResource'])
.factory('userService',function () {
var Users =[];
return{
getUsers:function(){
return $http.get("http://localhost:26309/api/User/getAll/").then(function (response) {
users=response;
return users;
});
},
getUser : function(UserName) {
return $http.get("http://localhost:26309/api/User/getUserByNom/" + UserName).then(function (serviceResp) {
return serviceResp.data;
});
}
}
})
ListeUsers.html
<ion-list>
<ion-item ng-repeat="user in Users"
>{{user.nom}}</ion-item>
</ion-list>
i can't find the problem
There are 2 issues you need to fix here for your app to work:
You need to correct he default fallback url from /app/ListeUsers to /ListeUsers because /app/ListeUsers path will be valid if the state was a child-state of app. See more details here: https://github.com/angular-ui/ui-router/wiki/Nested-States-and-Nested-Views
Your service methods are returning promises. You cannot assign a promise to a $scope variable and expect the app to be working. Change your controller code to use the parameter from the .then method callback of the returned promise as below:
angular
.module('starter.controllers', ['starter.services'])
.controller('UsersCtrl', function($scope,userService) {
userService.getUsers()
.then(function (response) {
$scope.Users= response;
});
});

Angularjs - General structure (route angular)

I am new in angular, want to do the next web site in angular
This would be the main structure:
The snippet1 is always fixed
The snippet3 is the dynamic part
If i click in the link1 or link2 of the snippet2,load would be in the snippet3 ().
Now I expose my doubt:
If i click in icons the snippet1, the load web page would be in snippet4.
Like the image:
Error, when i try install "express cors":
How could do it?
Prerequisites:
Node.js
Step #1: Setup a new project directory
app.js
css (folder)
main.css
snip3.css
snip4.css
ctrl (folder)
snip3Ctrl.js
snip4Ctrl.js
index.html
nodeServer.js
partials (folder)
snip3.html
snip4.html
Step #2: Install npm packages
From your project directory, run:
npm install express cors
Step #3: Copy and paste code
app.js
var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/snip3.html',
controller: 'snip3Ctrl'
})
.when('/snip3', {
templateUrl: 'partials/snip3.html',
controller: 'snip3Ctrl'
})
.when('/snip4', {
templateUrl: 'partials/snip4.html',
controller: 'snip4Ctrl'
})
.otherwise({ template: '<h1>Not Found</h1>' });
});
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Angular Routing Demo</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css">
<script src="http://code.angularjs.org/1.5.0/angular.js"></script>
<script src="http://code.angularjs.org/1.5.0/angular-route.js"></script>
<script src="app.js"></script>
<link rel="stylesheet" href="css/main.css" />
<script src="ctrl/snip3Ctrl.js"></script>
<link rel="stylesheet" href="css/snip3.css" />
<script src="ctrl/snip4Ctrl.js"></script>
<link rel="stylesheet" href="css/snip4.css" />
</head>
<body>
<div class="container" style="height: 100%;">
<nav id="navbar" class="navbar navbar-responsive">
<!-- snippet #1 here -->
</nav>
<div style="height: 200px;"></div>
<ng-view></ng-view>
</div>
</body>
</html>
nodeServer.js
var express = require('express'), cors = require('cors'), app = express();
app.use(cors());
app.use("/", express.static(__dirname));
app.listen(8080, function(){
console.log('CORS-enabled web server listening on port', 8080);
});
snip3Ctrl.js
angular.module('app').controller('snip3Ctrl', function($scope, $http) {
});
snip4Ctrl.js
angular.module('app').controller('snip4Ctrl', function($scope, $http) {
});
Step #4: Run the node server
From your project directory, run:
node nodeServer.js
Done!
It will serve your page to localhost:8080 by default. In case I forgot anything, post a comment and I will try to update the answer.
Try using ui-router for the routes.
In the main index.html, add the header navbar, and let the links manipulate the state of the application.
<body ng-controller="AppController">
<header>
<a ui-sref="Snippet4"></a>
</header>
<div ui-view></div>
</body>
That's the starting point for the html.

Failed to load template with UI-Router

In my index.html I'm calling scripts ui-bootstrap-tpls.min.js version 0.14.3 and below, angular-ui-router.min.js version 0.2.15.
<!DOCTYPE html>
<html lang="pt-BR" ng-app="main">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="icon" href="./favicon.ico">
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.9/angular.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.14.3/ui-bootstrap-tpls.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
<script type="text/javascript" src="./js/angular/main.js"></script>
<script type="text/javascript" src="./js/angular/controllers/carousels.js"></script>
</head>
<body ui-view="outside"></body>
</html>
And in the script main.js I call the directives ui.bootstrap and ui.router.
var app = angular.module("main", [
"ui.bootstrap",
"ui.router"
]);
And that's my route:
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/home");
$urlRouterProvider.when("/", "/home");
$stateProvider.state("site", {
url: "/",
views: {
"outside#": {
templateUrl: "./pages/site/index/read.html"
}
}
}).state("home", {
parent: "site",
url: "home",
views: {
"inside#site": {
templateUrl: "./pages/site/home/read.html"
}
}
});
});
But when I go on any page to make call from any element of the UI Bootstrap, whether tooltips or carousel, returns me an error saying it can not load the template.
This started after I started using the UI Router.
Does anyone know how to solve this problem?
-- Edited --
I could finally figure out what is causing the problem.
In the script main.js I clean the cache of templates using the following code:
app.run(function($rootScope, $templateCache) {
$rootScope.$on("$stateChangeStart", function() {
$templateCache.removeAll();
});
});
And that is exactly what is causing all my problem.
But how can I clear the cache of templates in UI Router without the UI Bootstrap stop working?

Is there something like initialize module once in angular?

Can I have loading some data once in angular module? I tried to use .run() but it gets called whenever page is accessed. For Example: say there are 2 html pages belonging to same module:
TestPage1.html:
<html ng-app="myApp">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="js/angular.min.js"></script>
<script src="js/jquery-1.8.2.js"></script>
<script src="js/app.js"></script>
</head>
<body>
<p><a ng-href="TestPage2.html">Go to Page2</a></p>
</body>
</html>
TestPage2.html:
<html ng-app="myApp">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="js/angular.min.js"></script>
<script src="js/jquery-1.8.2.js"></script>
<script src="js/app.js"></script>
</head>
<body>
<p><a ng-href="TestPage1.html">Go to Page1</a></p>
</body>
</html>
app.js:
var myApp = angular.module('myApp', []);
var cnt = 0;
myApp.run(['$rootScope', '$http', function(scope, $http) {
if(scope.loggedIn == undefined || scope.loggedIn == null) {
$http.get('rest/userData').success(function(data) {
cnt++;
alert(cnt);
scope.loggedIn = true;
});
}
}]);
When I navigate from one page to another this .run() is getting called again and again with cnt as 1. Is it possible to have it called once in life- time of module getting initialized? Or what is the other way?
It seems you are missing some basics such as a controller. The typical angular setup is having an ng-view for your app and loading the other pages via routing. Here is a simple example:
http://beta.plnkr.co/edit/RnZWeWxTJFri49Bvw50v?p=preview
app.js
var app = angular.module('myApp', []).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {templateUrl: 'TestPage1.html', controller: Page1Ctrl});
$routeProvider.when('/view2', {templateUrl: 'TestPage2.html', controller: Page2Ctrl});
$routeProvider.otherwise({redirectTo: '/view1'});
}]).run(function () { // instance-injector
alert('only run on first page load this is where you load data or whatever ONE time'); // this only runs ONE time
})
function MainCtrl($scope) {
$scope.name = 'main';
}
function Page1Ctrl($scope) {
$scope.name = 'page 1';
}
function Page2Ctrl($scope) {
$scope.name = 'page 2';
}
HTML:
<html ng-app="myApp" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="style.css">
<script>document.write("<base href=\"" + document.location + "\" />");</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
This is the main page. Main nav:
<a ng-href="#/view1">Go to Page1</a>
<a ng-href="#/view2">Go to Page2</a>
<div ng-view></div>
</body>
</html>
You will notice in the html there is an ng-view, when a route is encountered such as #/view the routeprovider looks it up and provides the correct template and calls the appropriate controller. I believe this is the kind of setup you are trying to achieve.

Resources