Why does not my html file load in this AngularJs Project? - javascript

My code looks like this:
index.html
<!doctype html>
<html ng-app="myApp">
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"> </script>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular-route.min.js"></script>
<script src = "js/main.js"></script>
</head>
<body>
<div>
<div data-ng-view></div>
</div>
</body>
</html>
main.js
var app = angular.module('myApp', ['ngRoute']);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider
.when('/view1', {
controller : 'SimpleController',
templateUrl : 'templates/view1.html'
})
.when('/view2', {
controller : 'SimpleController',
templateUrl : 'templates/view2.html'
})
.otherwise({ redirectTo : '/view1' });
}]);
app.controller('SimpleController', function ($scope) {
$scope.customers = [
{name : "John Doe", city : "San Francisco"},
{name : "John Bollinger", city : "Phoenix"},
{name : "Jane Doe", city : "Washington"}
];
$scope.addCustomer = function () {
$scope.customers.push(
{name : $scope.newCustomer.name,
city : $scope.newCustome.city
}
)
}
});
In my js folder, I have another folder called templates. In this we have 2 html files.
view1.html
<div class="container">
<h1>View 1</h1>
Enter a name to search the list
<input type="text" data-ng-model="custName" />
<ul>
<li data-ng-repeat="cust in customers | filter : custName | orderBy : 'name' ">
{{ cust.name }} - {{ cust.city }}
</li>
</ul>
<br />
Customer name: <br />
<input type="text" data-ng-model="newCustomer.name" />
Customer city: <br />
<input type="text" data-ng-model="newCustomer.city" />
<br />
<button data-ng-click="addCustomer()">Add Customer</button>
</div>
and finally...
view2.html
<div class="container">
<h1>View 2</h1>
Enter a name to search the list
<input type="text" data-ng-model="custName" />
<ul>
<li data-ng-repeat="cust in customers | filter : custName | orderBy : 'city' ">
{{ cust.name }} - {{ cust.city }}
</li>
</ul>
</div>
Any ideas why this isn't working? I tried fixing the issue with the ng-route but that didnt work either.
When I open the file, the URL goes to index.html#/view1 indicating the route works, but the webpage is completely empty. None of the html elements load.
Edit:
This is the error I get in developers mode:
XMLHttpRequest cannot load angular.js:8632 file:///E:/Learning%20AngularJs/templates/view1.html. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
Note, I do have another templates folder in the directory with index.html containing the 2 view html files.

There is nothing wrong with your code. The problem is you need to host this in a web server i think you are trying to open it from file explorer
You can deploy this in IIS or any other webserver and try.
Or you can follow below steps
make sure you install node js
Open command prompt
Navigate to your root directory
Run the below commands
npm install connect
npm install serve-static
create a file called server.js. put below code
var connect = require('connect'), serveStatic = require('serve-static');
var app = connect();
app.use(serveStatic('.'))
app.listen(5000);
browse http://localhost:5000
It should work. I was able to do this using the code you have given

Related

AngularJS Routing based on Checkbox Selection

I am trying to learn Angular JS with an HTML Sample. I would like the user to fill out some basic information, and based on the checkbox they select, it will load a form page using the UI Routing. It will generate links to navigate the page automatically, based on the checkboxes selected. Then, once the form is complete it should save in a directory on the server, and download to the user computer.
I got the form to show all data as json array, but now nothing is working after trying to add the ability to create the checklist links, as navigation, and saving?
App.js
create our angular app and inject ngAnimate and ui-router
angular.module('formApp', ['ngAnimate', 'ui.router'])
//configuring our routes
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
// route to show our basic form (/form)
.state('form', {
url: '/form',
templateUrl: 'form.html',
controller: 'formController'
})
// nested states
// each of these sections will have their own view
// url will be nested (/form/profile)
.state('form.profile', {
url: '/profile',
templateUrl: 'form-profile.html'
})
// url will be /form/interests
.state('form.interests', {
url: '/interests',
templateUrl: 'form-interests.html'
})
// url will be /form/payment
.state('form.payment', {
url: '/payment',
templateUrl: 'form-payment.html'
});
// catch all route
// send users to the form page
$urlRouterProvider.otherwise('/form/profile'); })
// our controller for the form //
.controller('formController', function ($scope) {
// we will store all of our form data in this object
$scope.prefContactArray = [];
$scope.prefContactArray.push({ name: "Text", reply: "Great we'll text you.", isDefault: false });
$scope.prefContactArray.push({ name: "Email", reply: "Great we'll send you an email!", isDefault: false });
$scope.prefContactArray.push({ name: "Phone", reply: "Great we'll give you a call.", isDefault: false });
$scope.selectedprefContact = $scope.prefContactArray.name;
$scope.selectedprefContactReply = $scope.prefContactArray.reply;
$scope.fruitsList = [
{ id: 1, name: 'Apple', url: 'form/profile.html', state:'.profile' },
{ id: 2, name: 'Banana', url: 'form/interests.html', state:'.interests' },
{ id: 3, name: 'Guava', url: 'form/payment.html', state:'payment' }
];
$scope.selected = {
fruitsList: []
};
$scope.checkAll = function () {
$scope.selected.fruitsList = angular.copy($scope.fruitsList);
};
$scope.uncheckAll = function () {
$scope.selected.fruitsList = [];
};
$scope.create = function () {
var aTag = document.createElement('a ui-sref-active="active" ui-sref="fruitsList.state"
alt="fruitsList.name"');
status-buttons.appendChild(aTag);
$state.go($scope.selected.fruitsList.url);
};
$scope.formData = {};
$scope.submit = function downloadFile(fileName, urlData) {
var aLink = document.createElement('a');
var evt = document.createEvent("HTMLEvents");
evt.initEvent("click");
aLink.download = fileName;
aLink.href = urlData;
aLink.dispatchEvent(evt);
}
var data = $scope.formData;
downloadFile('test.csv', 'data:text/csv;charset=UTF-8,' + encodeURIComponent(data));
});
Form.html
<div id="form-container">
<div class="page-header text-center">
<h2>Let's Be Friends</h2>
<!-- the links to our nested states using relative paths -->
<!-- add the active class if the state matches our ui-sref -->
<div id="status-buttons" class="text-center">
<a ui-sref-active="active" ui-sref=".profile"><span>1</span> Profile</a>
<a ui-sref-active="active" ui-sref=".interests"><span>2</span> Interests</a>
<a ui-sref-active="active" ui-sref=".payment"><span>3</span> Payment</a>
</div>
</div>
<div id="splitscreen">
<!-- use ng-submit to catch the form submission and use our Angular function -->
<form id="signup-form" ng-submit="createQuote()">
<div id="userPanel" class="col-md-6" style="background-color:#999; z-index:2;">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" ng-model="formData.name">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" name="email" ng-model="formData.email">
</div>
<div class="form-group">
<label for="email">Phone</label>
<input type="text" class="form-control" name="email" ng-model="formData.phone">
</div>
<div class="form-group">
<label for="email">Website</label>
<input type="text" class="form-control" name="email" ng-model="formData.web">
</div>
<div ng-repeat="prefContact in prefContactArray">
<label>
<input type="radio" ng-value="prefContact.reply" ng-model="$parent.selectedprefContact" />
{{prefContact.name}}
</label>
</div>{{selectedprefContact | json}}
<div>
<label ng-repeat="fruit in fruitsList">
<input type="checkbox" checklist-model="selected.fruitsList" checklist-value="fruit.id"
ng-click="create()" /> {{fruit.name}}<br />
</label>
<button ng-click="checkAll()">Check all</button>
<button ng-click="uncheckAll()">Uncheck all</button> <br />
{{selected.fruitsList}}
</div>
</div>
</div>
<pre>
{{ formData }}
</pre>
<div id="questions" class="col-md-6">
<!-- our nested state views will be injected here -->
<div id="form-views" ui-view></div>
</div> </form>
</div>
</div>
<!-- show our formData as it is being typed -->
Submit Button Page
Thanks For Your Money!
<button type="submit" class="btn btn-danger">Submit</button> </div>
Index
<!-- CSS -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootswatch/3.1.1/darkly/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<!-- JS -->
<!-- load angular, nganimate, and ui-router -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-animate.min.js"></script>
<script src="app.js"></script>
</head>
<!-- apply our angular app --> <body ng-app="formApp">
<div class="container col-md-12">
<!-- views will be injected here -->
<div class="col-md-12" ui-view></div>
</div>
In your create() function you use $state.go($scope.selected.fruitsList.url) which will change to the new state, however the value is the template path rather than the state path.
You should use $state.go($scope.selected.fruitsList.state) because the 'to' parameter of $state.go() should be the name of the state that will be transitioned to or a relative state path. If the path starts with ^ or . then it is relative, otherwise it is absolute.
$state
As #Andorov already mentioned, you need $state to navigate. UI Router has offers this service to make it easy for you to go from one state (or route, or page) to another. Add the dependency to your controller like so:
.controller('formController', function ($scope, $state) {
You are now able to say something like $state.go('form.payment') in your controller. This will navigate the person to the Payment form.
So all you would need to do now is when they submit the form (i.e. inside your $scope.createQuote() function which you haven't included in the code yet), find out what state you should go to and end with $state.go(stateToGoto).
Tip:
When I started out with UI router and AngularJs, I just made every route its own page, not using children. If you would do that you would get:
A route for your form
A route for every page it could go to.
Every route has its own controller, which makes it easy to put code in the right place. I don't like sharing the controller between children as it just makes it more difficult to understand which part of the code is for which child.
Does this help?

angularjs: controllers with routeproviders

I am trying to load two controllers dynamically using routeproviders in angularjs. But it only returns a blank page instead of showing the default page. What is the error I have done? The code is given below.
Index.html
<html ng-app="demoController">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<body>
<div ng-view=""></div>
</body>
<script>
var demoController = angular.module('demoController',[]);
demoController.config = function ($routeProvider){
$routeProvider
.when('/customers',{
controller:'sampleController',
templateUrl:'template/customers.html'
})
.when('/location',{
controller:'nextController',
templateUrl:'template/location.html'
})
.otherwise({redirect:'/customers'});
});
var dumpControllers={};
dumpControllers.sampleController=function ($scope){
$scope.customers=[
{name:'John Smith', country:'Denmark', worth:'5000000'},
{name:'John Lewis',country:'England',worth:'10000000'},
{name:'Rick Evans',country:'America',worth:'6000000'}
];
};
dumpControllers.nextController=function ($scope){
$scope.location=[{city:'Chennai'},{city:'Bangalore'},{city:'Mumbai'}];
}
demoController.controller(dumpControllers);
</script>
location.html
<ul>
<li ng-repeat="loc in location | orderBy: 'city'">{{ loc.city }}</li>
</ul>
customers.html
<input type="text" ng-model="searchName">
<ul>
<li ng-repeat="cust in customers | filter:searchName | orderBy:'country'">{{ cust.name }} - {{ cust.country }} - {{ cust.worth | currency:"$":2 }}</li>
</ul>
Can help me with this working? Thanks!!!
Put this in your head after you load angular:
<script src="https://code.angularjs.org/1.3.9/angular-route.js"></script>
and inject the module:
var demoController = angular.module('demoController',['ngRoute']);
and another problem:
.when('/location',{
controller:'nextController',
templateUrl:'template/location.html'
})
.otherwise({redirect:'/customers'});
};//Removed parenthesis

Angular Data Binding problems

So I want the user coming to my portfolio to enter their first name on the index.html page. Then I will welcome the user on the welcome page. How do I pass the information from the index.html to the welcome.html. I'm a novice at angular, your will be very grateful!
index.html:
<header ng-controller="UserName as myApp">
<form >
<label><h1>Enter Your First Name: </h1></label>
<input type="text" ng-model="user.name" name="clients" autofocus />
<button>CLICKME</button>
</form>
<h1>{{user.name}}</h1>
</header>
welcome.html:
<div class="container">
<div class="propic"></div>
<div class="blurb">sfdvsdfvsdv <span ng-controller="FirstCtrl">{{data.message}}</span> fsdv sdfvsdfv sdf fs vsdfv sdfvf f vsdfv sdfv sfdv dsv fdv</div>
</div>
app.js:
(function(){
var myApp = angular.module('myApp', []);
myApp.controller('UserName', function(){
this.product = name;
});
var User = {
name: ""
}
});
Here is the github: https://github.com/wiafe/Portfolio
And here is the page: http://wiafe.github.io/Portfolio/
PS: The h1 that's being bind in index.html can be ignored I was just testing something.

Route not working in angular.js with node/express

I am getting a 404 and cannot figure out why. I know my mongoDB server and node server are working because I can query and view my services. Now I am trying to implement an angular.js frontend on top of the services but I keep getting a 404 when I try to access my "home state".
// Configure the app to use routing. These $ tags are referencing the angular ui-router import.
app.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
// tells your route what controller to use when it gets there
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl'
resolve: {
postPromise: ['posts', function(posts){
return posts.getAll();
}]
}
});
$stateProvider
.state('posts', {
url: '/posts/{id}',
templateUrl: '/posts.html',
controller: 'PostsCtrl'
});
// .otherwise means "route to this place if the url is anything else" || like an if/else for url routing
$urlRouterProvider.otherwise('home');
}]);
This is some code from app.js that is throwing the code. Standard express generated code here.
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
This is the javscript that should be displaying, which is located in my index.ejs view page in node.
<script type="text/ng-template" id="/home.html">
<div class="page-header">
<h1>Flapper News</h1>
</div>
<div ng-repeat="post in posts | orderBy:'-upvotes'">
<span class="glyphicon glyphicon-thumbs-up"
ng-click="incrementUpvotes(post)"></span>
{{post.upvotes}}
<span style="font-size:20px; margin-left:10px;">
<a ng-show="post.link" href="{{post.link}}">
{{post.title}}
</a>
<span ng-hide="post.link">
{{post.title}}
</span>
<span>
Comments
</span>
</div>
<form ng-submit="addPost()"
style="margin-top:30px;">
<h3>Add a new post</h3>
<div class="form-group">
<input type="text"
class="form-control"
placeholder="Title"
ng-model="title"></input>
</div>
<div class="form-group">
<input type="text"
class="form-control"
placeholder="Link"
ng-model="link"></input>
</div>
<button type="submit">Post</button>
</form>
</script>
Also for reference, my imports on the index.ejs page
<head>
<title>Flapper News</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>
<script src="/javascripts/angularApp.js"></script>
<style> .glyphicon-thumbs-up { cursor:pointer } </style>
</head>
I am baffled by this 404 because I feel like I have a good understanding of this in-line templating routing set up. I have tried everything I can think of and nothing will resolve this 404.
GET /home 404 19.131 ms - 1246
It looks like you made the same mistake I did following this tutorial: you deleted the root route in routes/index.js which is need to serve up the initial index.ejs file. Here it is to add back to your route:
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});

Argument controller is not function, got undefined at Error

I'm using AngularJS + Laravel for my web-application. AngularJS install in public/app folder, the view for my web-application is not from public/app, is from Laravel/app/view folder.
-views
--web-app
---partials
---chat-rooms.blade.php
--index.blade.php
Index.blade.php
<body ng-app='chatApp'>
<div class="page-header">
<h1> Chat application </h1>
</div>
<div ng-view class="container"></div>
{{ HTML::script('app/libs/angular/angular.min.js')}}
{{ HTML::script('app/libs/angular-route/angular-route.min.js')}}
{{ HTML::script('app/scripts/app.js')}}
{{ HTML::script('app/scripts/controllers/chat-rooms.js')}}
</body>
Chat-rooms.blade.php
<div class="row">
<div class="col-md-12">
<select class="form-control" ng-model="selectedChatRoom" ng-options="chatRoom.name for chatRoom in chatRooms">
</select>
<button type="button" ng-click="selectChatRoom(selectedChatRoom)">Select chat room</button>
</div>
<div class="col-md-12">
<input type="text" class="form-control" ng-model="chatRoom.name" placeholder="Enter chat room name">
<button type="button" ng-click="createChatRoom(chatRoom)">Create</button>
</div>
My app.js is from public/app folder :
'use strict';
angular.module('chatApp', ['ngRoute'])
.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/chat-rooms',
controller: 'ChatRoomsCtrl'
})
.when('/chat-room/:chatRoom', {
templateUrl: 'partials/chat-room.html',
controller: 'ChatRoomCtrl'
});
});
The problem now is "ChatRoomsCtrl" cause this problem, the function is undefined.
Here's the js:
'use strict';
angular.module('chatApp')
.controller('ChatRoomsCtrl', function($scope, ChatRoom, $location) {
var chatRoomsLoaded = function(chatRooms) {
$scope.chatRooms = chatRooms;
}
var handleErrors = function(response) {
console.error(response);
}
$scope.selectChatRoom = function(chatRoom) {
$location.path('chat-room/' + chatRoom.id);
}
$scope.createChatRoom = function(chatRoom) {
ChatRoom.create(chatRoom).then($scope.selectChatRoom);
}
ChatRoom.getAll()
.then(chatRoomsLoaded)
.catch(handleErrors);
});
Again, everything seems work, the front-end can work, but the backends couldn't. The create button "ng-click" doesn't toggle at all. Seems like controller is causing this.
Part of my index.blade.php is actually put inside my video template.
My video template consist of videoController and route...
VideoController
public function getChatRoom()
{
return View::make('chat-app.partials.chat-rooms');
}
Route
Route::get('video/{slug}', array(
'as' => 'showVideo',
'uses' => 'VideoController#show'
));
Route::get('video/partials/chat-rooms', array(
'uses' => 'VideoController#getChatRoom'
));
When I load the chat-rooms, the web address must be video/partials/chat-rooms.. Currently I'm surfing the video template, part of it was chat-app, the web address is video/{slug}/ which slug could be any name...
ERROR : Click here to view the error

Categories