ng-view Angular not showing the text output - javascript

<html>
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="angular-route.js"></script>
</head>
</head>
<body ng-app="myApp" ng-controller="cont1">
<a href=#dogs>dogs</a> <a href=#cats>cats</a>
<div ng-view></div>
<script>
angular.module("myApp", ['ngRoute']).config ('$routeProvider',function($routeProvider){
$routeProvider.when("/dogs", {templateUrl: "one.html"})
.when("/cats", {templateUrl: "two.html"})
.otherwise("/cats", {redirectTo: "/dogs"})
});
app.controller("cont1", function($scope){ $scope.model = {message: "This is my app One!!!"} });
</script>
</body>
</html>
I am unable to get the message in paragraph 'Here are the cats' or 'Here are the dogs' on clicking the two links; these files are saved as one.html and two.html in the same folder.
I have downloaded and added the angular-route.js file in the same folder. Kindly help!
I have put controllers in routerProvider but it is not necessary, and adding it to it wont run! :(

You are forgetting to insert the controllers for your templates inside the object in when. See below:
<html>
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="angular-route.js"></script>
</head>
</head>
<body ng-app="myApp" ng-controller="cont1">
<a href=#dogs>dogs</a> <a href=#cats>cats</a>
<div ng-view></div>
<script>
angular.module("myApp", ['ngRoute']).config ('$routeProvider',function($routeProvider){
$routeProvider.when("/dogs", {
templateUrl: "one.html",
controller: "cont1"
})
.when("/cats", {
templateUrl: "two.html",
controller: "cont1"
})
.otherwise("/cats", {redirectTo: "/dogs"})
});
app.controller("cont1", function($scope){ $scope.model = {message: "This is my app One!!!"} });
</script>
</body>
</html>

If you're opening this html file directly in the browser, it won't work. This is because your template files will be loaded using AJAX. To make sure the user's data from one site cannot be fetched by a malicious other site, AJAX requests must adhere to the Same origin policy. The minute details of this policy are outside the scope of this answer, but it means that one site page can't make requests to another site. Files loaded directly from disk (loaded using the `file://' url scheme) don't have an origin so the cross origin policy check will always fail.
To solve this problem, put your files on a server, and try acessing them from there. If you're using a mac, you canuse Python's simple http server, which comes preinstalled on your mac. On windows, you can use mongoose.

When you use the minify-proof syntax for angular you pass the parameters as an array, so instead of:
config('$routeProvider',function($routeProvider){
$routeProvider.when("/dogs", {
...
});
you needed:
config(['$routeProvider',function($routeProvider){
$routeProvider.when("/dogs", {
...
}]);
http://plnkr.co/edit/7NiWduPXCIKutSF243Hg?p=preview

I checked it out with Team. I just had to remove the controller from the top part of the code in Html file, and it would work fine.
<body ng-app="myApp" ng-controller="cont1">
should be turned to ...
<body ng-app="myApp">
Thanks buddies for helping me though!

Related

Angular ng-Route doesn't work in a very simple example

I am learning angular.js and found an example on w3c.school
http://www.w3schools.com/angular/tryit.asp?filename=try_ng_routing
But when I try to test it it doesn't work,
I made two .htm files simply containing one word, for example "RED", or "GREEN". As simple as this example is I cannot get it to work. I think that it might be the libraries I am using
<!DOCTYPE html>
<html>
<!-- JavaScript Files -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular-route.js"></script>
<body ng-app="myApp">
<p>Main
</p>
Red
Green
Blue
<div ng-view></div>
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider.when("/", {
templateUrl: "test.html"
}).when("/red", {
templateUrl: "red.htm"
}).when("/green", {
templateUrl: "green.htm"
});
});
</script>
</body>
</html>
In this case you are moving towards a page "red.htm" which,... Doesn't exist in your situation! The page is already there in the directory for W3School (http://www.w3schools.com/angular/red.htm for exmaple)
So what you need to do is to create a htm page called red.htm in the same directory and thus navigate to it using routing. If you want to make the same example copy the code of the page I linked and try to run it with both files on the same directory.
From the three files I was using (test.html, red.html, green.html) I finally noticed/understood that you mustn't self-reference the file you are writing the script in.
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider.when("/red", {
templateUrl: "red.htm"
}).when("/green", {
templateUrl: "green.htm"
});
});
</script>
Simply by removing the .when method for 'test.html' (which is the exact same file the code is in) the self-referencing stops, and the code is allowed to execute.

Angular ngRoute can't load template: Error [$compile:tpload]

I tried some simple Angular Routing, but I cant specify what's the error. Chrome just tells me that Angular can't compile the Template.
In the following Link you can see my directory structure.
directory-structure
-- angular.js
var testApp = angular.module('testApp', ['ngRoute']);
testApp.config(function($routeProvider){
$routeProvider.when('/list', {
templateUrl: 'pages/list.html',
controller: 'mainController'
}).when('/insert', {
templateUrl: 'pages/new.html',
controller: 'newController'
});
});
testApp.controller('mainController', function($scope){
$scope.message = 'main';
});
testApp.controller('newController', function($scope){
$scope.message = 'new';
});
--index.html
<!DOCTYPE html>
<html lang="en" ng-app="testApp">
<head>
<meta charset="UTF-8">
<title>Barfly</title>
<script src="/angular/angular.min.js"></script>
<script src="/angular-route/angular-route.min.js"></script>
<script src="/js/angularApp.js"></script>
</head>
<body ng-controller="mainController">
list
new
<div id="main">
<div ng-view></div>
</div>
</body>
</html>
This is my error,
Browser Error
Thank you in advance!
EDIT. Sorry, I didn't see your directory structure. Are you sure pages directory is accessible to the public? Should the pages directory be moved into public directory?
Old answer:
The error is saying the templateUrl /pages/list.html does not exists. You should either save a template file into /pages/list.html file or add an inline template in the html body like this:
<script type="text/ng-template" id="/pages/list.html">
my template here
</script>
I encountered a sort of similar problem: templateUrl files could be not loaded (all resources didn't). In my case it happened when app was loaded on a browser on a mobile device. It was caused by Content Security Policy restrictions (How does Content Security Policy work?)
I got the CSP to permit all resources except for the templates referenced by templateUrl.
I also tried loading the templates through the script directive (https://docs.angularjs.org/api/ng/directive/script), but to no avail.
Eventually I decided to embed the templates in the route itself, like this:
testApp.config(function($routeProvider){
$routeProvider.when('/list', {
template: '<li ng-repeat="etcetera"></li>',
controller: 'mainController'
});
});
<a data-target="#list">list</a>
<a data-target="#insert">new</a>

angularJS $http.get communicating with API

I am new to AngularJS and I am trying to understand it by studying sample codes.
Here I have one about $http.get, from the following link:
http://www.w3schools.com/angular/tryit.asp?filename=try_ng_customers_json
I just replaced url with one of my own but it did not work, and I am really confused, please help, thanks!
=========================
second edit: thanks to the answers, double ng-app is a mistake, but it is not the main reason for this problem. I think it has something to do with cross-site blocking, but I have turn it off on my API (I use codeigniter REST API and I set $config['csrf_protection'] = FALSE; ), I am not sure how to configure it.
<!DOCTYPE html>
<html>
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="customersCtrl">
<ul>
{{names}}
</ul>
</div>
<div ng-controller="myCtrl">
<ul>
{{names}}
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://www.w3schools.com/website/Customers_JSON.php")
.success(function (response) {$scope.names = response;});
});
app.controller('myCtrl', function($scope, $http) {
$http.get("https://manage.pineconetassel.com/index.php/api/v1/colors2.php")
.success(function (response) {$scope.names = response;});
});
</script>
</body>
</html>
The problem is that you have two "myApp" declarations.
From AngularJS documentation:
Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application.
So, you should move the ng-app="myApp" to the body element.
However, once you've done that you probably still won't see any result because you are cross-site scripting and browsers will (by default) block the second request.
Two ng-app directive on single page will execute the first one, 2nd one will get ignored.
Remove ng-app="myApp" from both div of your html and use angular.bootstrap to bootstrap angular app on html page using below code.
Code
angular.element(document).ready(function() {
angular.bootstrap(document, ['myApp']);
});

Single Page Application View Location

I think I have a gross misunderstanding as to how routing in AngularJS works, and SPA's altogether.
I had thought with my simple routing :
$routeProvider
.when('/home', {
templateUrl: 'app/views/home.html',
controller: 'homeController'
})
.when('/login', {
templateUrl: 'app/views/login.html',
controller: 'loginController',
})
I had thought that when I went to /login, angular made an ajax call to grab the html page it needed. However, I don't see any calls going through fiddler, and that doesn't really make sense.
But I can't seem to locate where the pages are in my Chrome Developer Tools, nor find the correct word combination to get a suitable answer through google. Can someone clear this up for me?
if it helps, here's the body of my layout page:
<body ng-cloak>
<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
...nav stuff
</nav>
<br/><br/>
<div class="container body-content" ng-view></div>
<!-- 3rd party scripts -->
<script src="Scripts/angular.js"></script>
<script src="Scripts/angular-local-storage.min.js"></script>
<script src="Scripts/jquery-2.1.1.min.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
<script src="Scripts/angular-route.min.js"></script>
<!-- app main -->
<script src="app/app.js"></script>
<!-- controllers -->
<script src="app/controllers/homeControllers.js"></script>
<script src="app/controllers/loginController.js"></script>
<!-- services -->
<script src="app/services/modelErrorService.js"></script>
<script src="app/services/authInterceptorService.js"></script>
<script src="app/services/authService.js"></script>
</body>
EDIT
Sorry I may have been unclear. The code works fine. My question is, when angular routes you to a new page, where is it loading that html template from? Is it all delivered to the client at the get-go, or is it calling back to the server? If it is on the client, where is it stored?
If templateUrl is specified, Angular will look into the $templateCache for the template and load it from there if found. If not found, it will try to fetch it from the server, store it in $templateCache for future access and load it into view.
Templates can be put into Angular's $templateCache
when fetched from the server for the first time
by placing them in the HTML, in a <script type="text/ng-template"></script> element
by programmatically putting them into the $templateCahce (for whatever reason: performance, offline access etc)
Your code looks just fine.
Have you injected the ngRoute module into your application like so:
angular.module('your-app-name', ['ngRoute']);

Simple ng-include not working

Im playing with AngularJS for the first time, and im struggling to use ng-include for my headers and footer.
Here's my tree:
myApp
assets
- CSS
- js
- controllers
- vendor
- angular.js
- route.js
......
......
......
main.js
pages
- partials
- structure
header.html
navigation.html
footer.html
index.html
home.html
index.html:
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>AngularJS Test</title>
<script src="/assets/js/vendor/angular.js"></script>
<script src="/assets/js/vendor/route.js"></script>
<script src="/assets/js/vendor/resource.js"></script>
<script src="/assets/js/main.js"></script>
</head>
<body>
<div ng-include src="partials/structure/header.url"></div>
<div ng-include src="partials/structure/navigation.url"></div>
<div id="view" ng-view></div>
<div ng-include src="partials/structure/footer.url"></div>
</body>
</html>
main.js
var app = angular.module("app", ["ngResource", "ngRoute"]);
app.config(function($routeProvider) {
$routeProvider.when("/login", {
templateUrl: "login.html",
controller: "LoginController"
});
$routeProvider.when("/home", {
templateUrl: "home.html",
controller: "HomeController"
});
$routeProvider.otherwise({ redirectTo: '/home'});
});
app.controller("HomeController", function($scope) {
$scope.title = "Home";
});
home.html
<div>
<p>Welcome to the {{ title }} Page</p>
</div>
When i go on the home.html page, my header, nav and footer are not appearing.
You're doing an include of header.url instead of header.html. It looks like you want to use literals in the src attribute, so you should wrap them in quotes, as was mentioned in the comments by #DRiFTy.
Change
<div ng-include src="partials/structure/header.url"></div>
<div ng-include src="partials/structure/navigation.url"></div>
<div id="view" ng-view></div>
<div ng-include src="partials/structure/footer.url"></div>
to
<div ng-include src="'partials/structure/header.html'"></div>
<div ng-include src="'partials/structure/navigation.html'"></div>
<div id="view" ng-view></div>
<div ng-include src="'partials/structure/footer.html'"></div>
If this is not working, check the browser console if there are any 404's
I had a similar problem with a simple ng-include not rendering:
<div ng-include="views/footer.html"></div>
I wrapped the file path in single quotes and it now renders:
<div ng-include="'views/footer.html'"></div>
i had a similar problem that landed me here.
ng-include was not populating the contents of my partial, but there were no console errors, nor 404's.
then i realized what i did.
fix for me: make sure you have ng-app outside of the ng-include! so obvious. the price of being an Angular noob.
I also came across this issue. And this is what worked for me.
So instead of writing this:<div ng-include="'html/form.htm'"></div>
You want to add ng-app="". So it should look like this: <div ng-app="" ng-include="'html/form.htm'"></div>
I was struggling with the same issue and have done almost all what was advised in different stacks but it didn't work for me. On Console, I was getting the Error:
"Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource."
Later I realised, I have to use a local web server (MAMP, WAMP etc.) to make it work.
Please be careful of the above error message. Chances are you are not using a local web server to run you website.
I just figured this one out!
For me, I was using a CDN for importing my angular.min.js file that apparently wasn't working. I switched to:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
and included ng-app="" in my body tag:
<body ng-app="">
<div ng-include="'testfile.html'"></div>
and it's working fine now. Cheers!
Yes, without the '', ng would try to evaluate the contents inside the ng-include("")
This evaluation is another reason why you don't put {{}} inside these directives.
ng-include is not working in chrome as well as in explorer but works in Firefox, so this could be compatibility issues. To be sure, try generating the report in Firefox or Edge or another browser.
I Too had similar issue: Silly mistake was causing IT , I had below textArea
EG:
<textarea cols="3" type="text" id="WarehouseAddress" class="form-control" > `
Wasn't closed properly Corrected below :
<textarea cols="3" type="text" id="WarehouseAddress" class="form-control" ></textarea>
<div ng-switch="vm.frmDOA.isGenerateDebitNote">
<ng-include src="vm.showupload()"></ng-include>
</div>
Thought to post it may help any one I digged hours to solve ....
the ng-include file works for files fetched from the web server only (needs something like http://mywebsite/myinclude.html link).
It does not work if you fetch file from local folder directly (c:\myinclude.html will not work)
The ng-include directive should just work normal if you're viewing your file via some server (localhost or online) and NOT viewing your file directly under file system like (file:///yourpath/index.html).
This example from w3schools should work fine.

Categories

Resources