I can't send new datas with $http.post in AngularJS - javascript

I have theses codes:
app.js (routers):
(function(){
var pizzasApp = angular.module('pizzasApp',['ngRoute','app']);
//here is declared the routers
pizzasApp.config(['$routeProvider', function($routeProvider){
$routeProvider.
when('/pizzas',{
templateUrl: 'pizza-list.html',
controller: 'PizzasController'
}).
when('/',{
redirectTo:'/pizzas'
}).
when('/pizzas/:pizzaId',{
templateUrl: 'pizza-detail.html',
controller: 'PizzasDetailController'
}).
otherwise({
redirecTo: '/pizzas'
});
}]);
})();
configure.js (controllers):
(function(){
var app = angular.module('app',[]);
//In this controller is got all pizzas from JSON file and post new pizzas
app.controller('PizzasController',['$scope','$http',function($scope,$http){
$http.get('http://162.250.78.47/api/pizzas').success(function(data){
$scope.pizzas = data;
});
//WHEN CLICK THE BUTTON FORM FROM pizza-list.html THIS ADD NEW PIZZA. BUT THIS DOESN'T WORK
$scope.save = function(){
$http.post('http://162.250.78.47/api/pizzas',$scope.pizzas).then(function(data){
$location.path('/pizzas');
});
};
}]);
//In this controller I get a selected pizza with ingredients
app.controller('PizzasDetailController',['$scope','$http','$routeParams',function($scope,$http,$routeParams){
$scope.pizzaId = $routeParams.pizzaId;
$http.get('http://162.250.78.47/api/pizzas/'+$scope.pizzaId).success(function(data){
$scope.pizza = data;
});
$http.get('http://162.250.78.47/api/ingredients').success(function(ingr){
$scope.ingrs = ingr;
});
}])
})();
index.html (home):
<!DOCTYPE html>
<html lang="en" ng-app="pizzasApp">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="bootstrap-3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="bootstrap-3.2.0/css/bootstrap-theme.min.css">
<script type="text/javascript" src="jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="bootstrap-3.2.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="angular-route.min.js"></script>
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript" src="configure.js"></script>
<title>New Web Project</title>
</head>
<body>
<div ng-view></div>
</body>
</html>
pizza-list.html (pizza list and form to add new pizza):
<div ng-repeat="nombre in pizzas">
<p>{{nombre.name}}</p>
</div>
<!-- HERE IS THE PROBLEM -->
<form>
<label>Write the pizza name that you want add:</label></br>
<input type="text" ng-model="pizzas.name" placeholder="Pizza">
<button ng-click="save()">Add</button>
</form>
pizza-detail.html (pizza with ingredients):
<div>
<p>{{pizza.name}}</p>
<div ng-repeat="ing in pizza.ingredients track by $index">
<div ng-repeat="ingr in ingrs">
<div ng-if="ing == ingr._id">
{{ingr.name}}
</div>
</div>
</div>
</div>
My problem is that when I want to add a new pizza in the pizza-list.html form, it doesn't work.
Before in click 'Add' new Pizza:
After in click 'Add' new Pizza:
This error is translate to English like:
Blocked request from various sources: the same origin policy prevents read http://162.250.78.47/api/pizzas remote resource. This can be fixed by moving the action to the same domain or activating CORS.

The error has already answered your question(which you never asked). You are trying to submit data to a different host, other than your angular application is running.
In layman terms: you are running your application at localhost, but supplying data to 162.150.78.47. This is not allowed due to security restrictions.
Possible solutions:
1) Host everything on same domain(eg localhost)
2) Enable CORS on API side. I don't know what technology you use, but in C# you have to add [EnableCors] to your controller, which allows cross requesting.
3) Look into JSONP.

Related

How to migrate javascript from a multi-file example, in to a simple, single page?

I know this sounds like a ridiculously simple question, but there is a lot more to it than just a basic function call. I'm implementing authentication on a webapp using the Auth0 python example, they have a full example available here.
I completely understand the python Auth0 stuff, and can get all the details I require from the session, but I simply can NOT work out how to move this sample code in to my app using a simple "login" and "logout" button! The HTML from the sample app looks like this:
<html>
<head>
<script src="http://code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script src="https://cdn.auth0.com/js/auth0/8.6.0/auth0.min.js"></script>
<script type="text/javascript" src="//use.typekit.net/iws6ohy.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- font awesome from BootstrapCDN -->
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
<script>
var AUTH0_CLIENT_ID = '{{env.AUTH0_CLIENT_ID}}';
var AUTH0_DOMAIN = '{{env.AUTH0_DOMAIN}}';
var AUTH0_CALLBACK_URL = '{{env.AUTH0_CALLBACK_URL if env.AUTH0_CALLBACK_URL else "http://localhost:3000/callback" }}';
var API_AUDIENCE = '{{env.API_IDENTIFIER}}';
</script>
<script src="/public/app.js"> </script>
<link href="/public/app.css" rel="stylesheet">
</head>
<body class="home">
<div class="container">
<div class="login-page clearfix">
<div class="login-box auth0-box before">
<img src="https://i.cloudup.com/StzWWrY34s.png" />
<h3>Auth0 Example</h3>
<p>Zero friction identity infrastructure, built for developers</p>
<a class="btn btn-primary btn-lg btn-login btn-block">SignIn</a>
</div>
</div>
</div>
</body>
</html>
The Javascript that is running is contained in a seperate file that is read in on document load:
$(document).ready(function() {
var auth = new auth0.WebAuth({
domain: AUTH0_DOMAIN,
clientID: AUTH0_CLIENT_ID
});
$('.btn-login').click(function(e) {
e.preventDefault();
auth.authorize({
audience: 'https://'+AUTH0_DOMAIN+'/userinfo', // you can also set this on the .env file and put API_AUDIENCE instead
scope: 'openid profile',
responseType: 'code',
redirectUri: AUTH0_CALLBACK_URL
});
});
$('.btn-logout').click(function(e) {
e.preventDefault();
window.location.href = '/logout';
})
});
I don't want to use the standard HTML provided with the sample, all I want is a simple "login" button to, well log in the user, but for the life of me I simple don't understand how to make that happen. I want this to be as simple as possible, with all the javascript embedded in the page. I've tried the following, but it fails as the variable "e" is undefined, and I don't understand where it came from in the original example!
<html>
<head>
<script src="http://code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script src="https://cdn.auth0.com/js/auth0/8.6.0/auth0.min.js"></script>
<script type="text/javascript" src="//use.typekit.net/iws6ohy.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<p><button onclick="loginfunc()">Click me</button></p>
<script>
$(document).ready(function() {
var auth = new auth0.WebAuth({
domain: AUTH0_DOMAIN,
clientID: AUTH0_CLIENT_ID
});
},
</script>
<script>
function loginfunc(e) {
e.preventDefault();
auth.authorize({
audience: 'https://'+AUTH0_DOMAIN+'/userinfo', // you can also set this on the .env file and put API_AUDIENCE instead
scope: 'openid profile',
responseType: 'code',
redirectUri: AUTH0_CALLBACK_URL
});
}
</script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- font awesome from BootstrapCDN -->
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
<script>
var AUTH0_CLIENT_ID = '{{env.AUTH0_CLIENT_ID}}';
var AUTH0_DOMAIN = '{{env.AUTH0_DOMAIN}}';
var AUTH0_CALLBACK_URL = '{{env.AUTH0_CALLBACK_URL if env.AUTH0_CALLBACK_URL else "http://localhost:3000/callback" }}';
var API_AUDIENCE = '{{env.API_IDENTIFIER}}';
</script>
<script src="/public/app.js"> </script>
<link href="/public/app.css" rel="stylesheet">
</head>
<body class="home">
<div class="container">
<div class="login-page clearfix">
<div class="login-box auth0-box before">
<img src="https://i.cloudup.com/StzWWrY34s.png" />
<h3>Auth0 Example</h3>
<p>Zero friction identity infrastructure, built for developers</p>
<a class="btn btn-primary btn-lg btn-login btn-block">SignIn</a>
</div>
</div>
</div>
</body>
</html>
I'm guessing lines 6 and 7 of the original HTML is where all the "magic" is happening, I just don't know how to "read" what's going on there.
<script type="text/javascript" src="//use.typekit.net/iws6ohy.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
I understand this is a horrible, horrible question, but I've been looking at this for hours now and I'm just ready to give up, I can't look at it any more. For the life of me I don't understand why Auth0 didn't just make a super simple, all-on-on-page example that anyone can understand, not all this fancy bootstrap/css/html mess!
If anyone can help, I will be eternally grateful!
Thank you.
I did it!!!
So it turns out I was waaaaay off, it had nothing to do with the script lines I was focusing on. Here is the working code:
<html>
<head>
<script src="http://code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script src="https://cdn.auth0.com/js/auth0/8.6.0/auth0.min.js"></script>
<script>
function loginfunc() {
var auth = new auth0.WebAuth({
domain: AUTH0_DOMAIN,
clientID: AUTH0_CLIENT_ID
});
auth.authorize({
audience: 'https://'+AUTH0_DOMAIN+'/userinfo', // you can also set this on the .env file and put API_AUDIENCE instead
scope: 'openid profile',
responseType: 'code',
redirectUri: AUTH0_CALLBACK_URL
});
}
</script>
<script>
var AUTH0_CLIENT_ID = '{{env.AUTH0_CLIENT_ID}}';
var AUTH0_DOMAIN = '{{env.AUTH0_DOMAIN}}';
var AUTH0_CALLBACK_URL = '{{env.AUTH0_CALLBACK_URL if env.AUTH0_CALLBACK_URL else "http://localhost:3000/callback" }}';
var API_AUDIENCE = '{{env.API_IDENTIFIER}}';
</script>
</head>
<body >
<p><button onclick="loginfunc()">Click me</button></p>
</body>
</html>
Basically I just pulled the app.js code in to the main html file, then used a standard "onclick" button action to call the auth function. This is so much easier to read than the auth0 example.
I hope this makes the example clearer for someone else in the future. I find it really frustrating the developers confuse the core code example with completely unnecessary css and artys html formatting.

Multiple controllers working within ngRoute example

I have a small ngRoute example I am trying that to use multiple applications and controllers with. The first app/controller is for the main page, while the second set of app/controller is for the html that ngRoute loads up after pressing a button. However, it doesn't seem to be working. Code below:
Main Module
var app = angular.module("MainModule", ["ngRoute"]);
Main Controller
app.controller("MainController", function ($scope) {
});
app.config(function ($routeProvider) {
$routeProvider
.when('/customers', {
templateUrl: "customers.html",
controller: "CustomerController"
})
});
Customer Module
var CustomerModule = angular.module("CustomerModule", []);
Customer Controller
CustomerModule.controller("CustomerController", function ($scope) {
$scope.Test = "Hey";
$scope.CustomerArray = [
{ "firstName" : "John", "lastName" : "Williams", "Occupation" : "Fireman" },
{ "firstName" : "Louis", "lastName" : "Abrams", "Occupation" : "Policeman" }
]
});
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
<script src="scripts/MainModule.js"></script>
<script src="scripts/MainController.js"></script>
<link rel="stylesheet" type="text/css" href="MyCSS.css">
</head>
<body>
<div ng-app="MainModule">
<div id="TopDiv">Main Module</div>
<input type="button" value="Load Customers" />
<div ng-view></div>
</div>
</body>
</html>
customers.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="scripts/CustomerModule.js"></script>
<script src="scripts/CustomerController.js"></script>
</head>
<body>
<div ng-app="CustomerModule" ng-controller="CustomerController">
{{Test}}
<ul>
<li ng-repeat="x in CustomerArray">{{x.firstName x.lastName x.Occupation}}</li>
</ul>
</div>
</body>
</html>
Long bits of code there, but hopefully simple code. The output when I press the "Load Customer" button is literally {{Test}} with no array data to follow.
I am just now learning angular, so any help with this issue I would appreciate. I am just doing this for fun, to try to learn. So I suppose the issue is not pressing. :) Thanks!
I wrote out a working example using the code from the question as a base. There are quite a few adjustments that were made, so I will list each piece with a bit of explanation.
It is not necessary for each "page" to have it's own module. However, it is not a bad practice. To support the design you have here of one module for each view, I made the following changes:
Include the CustomerModule as a dependency in the MainModule (MainModule.js):
var app = angular.module("MainModule", ["ngRoute", "CustomerModule"]);
Load ALL scripts in the index.html:
<script src="scripts/MainModule.js"></script>
<script src="scripts/MainController.js"></script>
<script src="scripts/CustomerModule.js"></script>
<script src="scripts/CustomerController.js"></script>
With these changes, the $routeProvider is able to locate the CustomerController and instantiate it during a route change. The customers.html now does not have to create a controller, and can be stripped down to a complete partial. Also, the expression used in customers.html needed to be changed, and broken down into individual expressions for each property.
The final customers.html:
{{Test}}
<ul>
<li ng-repeat="x in CustomerArray">{{x.firstName}} {{x.lastName}} {{x.Occupation}}</li>
</ul>
Complete working sample on plnkr.co: http://plnkr.co/edit/EjwW9Fsc2DPhBejUETwB?p=preview
I'm not sure, but the problem is in your MainModule. It should be like this or so:
var app = angular.module("MainModule", ["ngRoute"]);
When you calling angular.module with only one parameter - it's only trying get module, not create.
And customers.html should only contains parts of you html, not full:
Full customers.html
{{Test}}
<ul>
<li ng-repeat="x in CustomerArray">{{ x.firstName }} {{ x.lastName }} {{ x.Occupation }}</li>
</ul>
And add move customer js files to index.html:
<script src="scripts/MainModule.js"></script>
<script src="scripts/MainController.js"></script>
<script src="scripts/CustomerModule.js"></script>
<script src="scripts/CustomerController.js"></script>
<link rel="stylesheet" type="text/css" href="MyCSS.css">
Hope, it helps.

How to load multiple page(cshtml) inside single page on button click with Angular.js?

I am creating crud operation in Angular.js with mvc with have following pages:
Index:This is the main page under which I want to display my list of employee page i.e _employeeList.cshtml.
AddNewEmployee.cshtml:This page will be used for creating new employee
EditEmployee.cshtml:For opening record in edit mode for particular employee.
All this pages I want to render inside Index.cshtml page i.e to create single page application.
When my page loads I want to display list of employees and when user clicks on Add Employee then I want to open new add employee page.
This is my current code:
Layout.cshmtl:
<!DOCTYPE html>
<html data-ng-app="empApp">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>#ViewBag.Title</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
<script src="~/Scripts/angular.js"></script>
</head>
<body>
#RenderBody()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
</body>
</html>
Index.cshtml:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1 style="margin-left:750px;">
List
</h1>
<input class="btn btn-primary" type="button" data-ng-click="AddEmployee()" value="Add Employee">
<div ng-controller="employeeListCtrl">
#Html.Partial("_employeeList")
</div>
<script src="~/AppScript/Module.js"></script>
<script src="~/AppScript/Service.js"></script>
<script src="~/AppScript/Employee.js"></script>
Module.js:
var app;
(function () {
app = angular.module("empApp", [])
config(function ($routeProvider) {
$routeProvider.when('')
{
}
});
})();
So basically I am stuck here. When user will click on Add Employee button, how I will load my AddNewEmployee.cshtml page in current index.cshtml page without page refresh?
Update:
Index.cshtml:
<h1 style="margin-left:750px;">
List
</h1>
<input class="btn btn-primary" type="button" data-ng-click="AddEmployee()" value="Add Employee">
#*<div ng-controller="employeeListCtrl">
#Html.Partial("_employeeList")
</div>*#
<ng-view></ng-view>
<script src="~/AppScript/Module.js"></script>
<script src="~/AppScript/Service.js"></script>
<script src="~/AppScript/EmployeeListController.js"></script>
Module.js:
var app = angular.module("empApp", ['ngRoute'])
.config(function ($routeProvider) {
$routeProvider.when('/employeelist',
{
templateUrl: 'Views/Home/_employeeList.cshtml',
controller: 'employeeListCtrl'
});
$routeProvider.otherwise({ redirectTo: '/Home' });
});
EmployeeListController:
app.controller('employeeListCtrl', function ($scope, crudService) {
alert()
});
But here my EmployeeListController doesnt gets called when my url is like this as shown in below pic and when I run my application why my url is like this as shown in below pic:
You can write a function in controller like
$scope.AddEmployee = function()
{
$location.url("AddNewEmployee");
}
After this you can check condition in config like
.when("/AddNewEmployee",{
templateUrl : "AddNewEmployee.cshtml",
controller : ""
})

angular/ionic - model does not update $scope in controller

I am a newb with angularjs and I am trying something that I believe should be very simple ... but turns out I am not figuring it out.
I have a $scope variable that I want to double bind (using ng-model) to a textarea. I was able to make it work on js fiddle websites but now on my code. I have tried to strip everything down to just a few lines and it still doesn't work, the controller is never updated.
this is my code:
js/main.js
var app=angular
.module('noclu', ['ionic', 'app.controllers'])
.config(function ($stateProvider, $urlRouterProvider){
$stateProvider
.state('menu.main', {
url: "/main",
views: {
'menuContent': {
templateUrl: 'templates/main.html',
controller: 'MainCtrl'
}
}
});
$urlRouterProvider.otherwise("/menu/main");
});
js/controller.js
angular
.module('app.controllers', [])
.controller('MainCtrl', function ($scope){
$scope.src='---';
$scope.get_feeds=function(){
//seems like that here "this" is actually the textarea ??
//$scope.src is always whatever has been set in the controller
console.log('this:'+this.src); //this output whatever I enter in the textarea
console.log('scope:'+$scope.src); //this always output '---'
};
});
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">
<link rel="icon" type="image/png" href="favicon.png">
<title>NoClu</title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/main.js"></script>
<script src="js/controllers.js"></script>
</head>
<body ng-app="noclu">
<ion-nav-view></ion-nav-view>
</body>
</html>
template/main.html
<ion-view view-title="NoClu" >
<ion-content class="padding" id="src-wrapper-center">
<div ng-class="vertical_center">
<div id="src-wrapper">
<div>
<div class="padding src-title">What are you in the mood for ?</div>
<div class="item" id="src-txt-wrapper">
<textarea id="src" ng-model="src"></textarea>
</div>
<button id="search" class="button button-block button-large button-balanced" ng-click="get_feeds()" >
Let's eat
</button>
</div>
</div>
</div>
</ion-content>
</ion-view>
UPDATE - I made it work, but why ?
I made it work by changing $scope.src='---'; to $scope.src={body:'---'}; and then changing the ng-modal to src.body. but.. WHY did not work the other way as it works for boolean?
Using directly $scope. is not a good practice in angularJS. There are various post of it, more concernign $scope inheritence.
For exemple : http://learnwebtutorials.com/why-ng-model-value-should-contain-a-dot
Therefore, your need to change your model like that :
$scope.myModel = {};
$scope.myModel.src = "---"
And your html to bind to myModel.src

Why does the controller not work when script is outside index.html?

I am puzzled with the following. When I copy the following tutorial from https://www.firebase.com/tutorial/#session/xa9242ucksy:
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.17/angular.min.js"></script>
<script src="https://cdn.firebase.com/js/client/1.1.1/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/0.8.0/angularfire.min.js"></script>
<link rel='stylesheet' href='/resources/tutorial/css/example.css'/>
</head>
<body ng-controller="MyController">
<!-- CHAT MARKUP -->
<div class='example-chat l-demo-container'>
<header>Firebase Chat Demo</header>
<div class='example-chat-toolbar'>
<label for='nameInput'>Username:</label>
<input ng-model='name' type='text' id='nameInput' placeholder='enter a username...'>
</div>
<ul id='example-messages' class='example-chat-messages'>
<li ng-repeat='msg in messages'>
<strong class='example-chat-username'>{{msg.from}}</strong>
{{msg.body}}
</li>
</ul>
<footer>
<input ng-model='msg' ng-keydown="addMessage($event)" type='text' id='messageInput' placeholder='Type a message...'>
</footer>
</div>
<script>
var myApp = angular.module("myApp", ["firebase"]);
myApp.controller('MyController', ['$scope', '$firebase',
function($scope, $firebase) {
//CREATE A FIREBASE REFERENCE
var ref = new Firebase("https://xa9242ucksy.firebaseio-demo.com/");
// GET MESSAGES AS AN ARRAY
$scope.messages = $firebase(ref).$asArray();
//ADD MESSAGE METHOD
$scope.addMessage = function(e) {
//LISTEN FOR RETURN KEY
if (e.keyCode === 13 && $scope.msg) {
//ALLOW CUSTOM OR ANONYMOUS USER NAMES
var name = $scope.name || 'anonymous';
//ADD TO FIREBASE
$scope.messages.$add({
from: name,
body: $scope.msg
});
//RESET MESSAGE
$scope.msg = "";
}
}
}
]);
</script>
</body>
</html>
And instead of having the script in the index page, but I remove that part, copy it to a file called app.js and save it, then it does not work anymore??? Basically in the head I add:
<head>
// OTHER
<script src="js/app.js"></script>
</head>
EDIT:
When I try the following then it does work. But again, what is wrong with the reference in the first place?? I want to store it in a JS folder.
<head>
// OTHER
<script src="app.js"></script>
</head>
EDIT 2:
Oke it seems that the problem is that I had multiple .js files stored. So the question becomes more on angularJS.
Basically I had multiple files because I want to split up my controllers, so when I have the following at the end of the index.html file:
DOES NOT WORK
<script src="js/maps.js"></script>
<script src="js/app.js"></script>
<script src="js/controller-fb.js"></script>
<script src="js/controller-maps.js"></script>
DOES WORK
<script src="js/app.js"></script>
My other files look similar to app.js
JavaScript will always be parsed as it gets to it in the page. In the case of the script you wrote, it is all going to be run as it is parsed.
Having it in the <head> section of your HTML means that none of the DOM exists at the point that it is run.
Put the <script src="app.js"></script> in the same spot as you have the <script> in the top sample, and it will work as it did before.

Categories

Resources