Am having a problem with angular. My angular code works fine when i run it alone but doesn't work when i access it on localhost with express. What happens is that it displays the html file alone.
my server code is :
*
var express = require('express'),
app = express();
app.get('/', function(req, res) {
res.sendfile('./app/client/main.html');
});
app.listen(3000, function() {
console.log('I\'m listening...');
})
my angular controller code is
var app = angular.module('tiks', []);
app.controller('mainController', function($scope){
$scope.posts = [];
$scope.newPost = {created_by: '', text: '', create_at: ''};
$scope.post = function(){
$scope.newPost.created_at = Date.now();
$scope.posts.push($scope.newPost);
$scope.newPost = {created_by: '', text: '', created_at: ''};
};
});
and the angularised html code is
<!--main.html-->
<!doctype html>
<html>
<head>
<title>Tiks</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="javascripts/tiks.js"></script>
</head>
<body ng-app="tiks">
<div id='main' ng-controller="mainController">
<form ng-Submit="post()">
<input required type="text" placeholder="Your name" ng-model="newPost.created_by" />
<textarea required maxlength="200" rows="3" placeholder="Say something" ng-model="newPost.text"></textarea>
<input class="button" type="submit" value="Chirp!" />
</form>
<div id="post-stream">
<h4>Tiks Feed</h4>
<div class='post' ng-repeat="post in posts | orderBy:'created_at':true" ng-class-odd="'odd'" ng-class-even="'even'">
<p>{{post.created_by}} says {{post.text}} at {{post.created_at}}</p>
</div>
</div>
</div>
</div>
</body>
</html>
please help
Your HTML is asking for javascripts/tiks.js at the script tag, but your server has no route configured to serve it.
Try checking the requests being done, for example using Google Chrome Developer tools network tab, and you will probably see a 404 error when the .js file is requested.
You should use express.static to serve files from folder instead of defining specific resources individually as you are doing for ./app/client/main.html.
app.use('/', express.static(__dirname + '/app/client/'));
then you would have to access http://localhost/main.html to access it.
Related
I am using stripe payment to process payments. I followed this GITHUB project and this blog.
My project has nested views and uses routers as well.
My project structure looks like
src
app
views
controllers
directives
index.html
app.js
The app.js is where angular module is loaded manually and has the routers.
app.js
var myApp = angular.module('myApp', ['ui.router', 'formData']);
myApp.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
// routers
}
The index.html is where the angular and stripe scripts are included
index.html
<head lang="en">
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<Script src="resources/angular.min.js"></Script>
<Script src="resources/angular-ui-router.min.js"></Script>
<script src="app.js"></script>
<script src="directives/formData/formData.js"></script>
<script type="text/javascript"
src="resources/angular-payments.js">
</script>
<script>
Stripe.setPublishableKey('key')
</script>
</head>
<div>
<div ui-view>
</div>
</div>
Now the formData directive is where I am trying to include the strip payment
formData.js
var formData = angular.module('formData',['angularPayments']);
formData.directive('formData',function(){
return {
restrict: 'EA',
scope: {},
replace: true,
link: function($scope, element, attributes){
},
controller: function($scope,$attrs,$http, $state){
//This is the callback for strip from the links above as followed
$scope.stripeCallback = function (code, result) {
console.log("inside cc callbakc");
if (result.error) {
console.log("credit card error");
window.alert('it failed! error: ' + result.error.message);
} else {
console.log(result);
console.log("credit card succes "+result.id);
window.alert('success! token: ' + result.id);
}
};
},
templateUrl: 'directives/formData/formData.tpl.html'
}
});
formData.tpl.html has another ui router
formData.tpl.html
<form id="signup-form" ng-submit="processForm()">
<!-- our nested state views will be injected here -->
<div ui-view></div
</form>
and one of the ui router html page is the payment page with this code
<form stripe-form="stripeCallback" name="checkoutForm">>
<input ng-model="number" placeholder="Card Number"
payments-format="card" payments-validate="card" name="card" />
<input ng-model="expiry" placeholder="Expiration"
payments-format="expiry" payments-validate="expiry"
name="expiry" />
<input ng-model="cvc" placeholder="CVC" payments-format="cvc" payments-validate="cvc" name="cvc" />
<button type="submit">Submit</button>
</form>
I get the validations working but nothing prints in the console when I hit submit. I guess the js is not being fired. Let me know if you need more information.
This will render as nested forms, which is invalid html. Most browsers are silently 'forgiving' of this by treating the inner form as a non-form element.
If you move the checkoutForm out from the signup-form, this should put you on the right track.
I'm developing an app with Riot Games API but this example it's done with REST Countries API. https://restcountries.eu/rest/v1/alpha/co
I use a MEAN.IO stack and this is my code:
test.html
<html ng-app="lolData">
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.1.3/material.indigo-pink.min.css">
<script defer src="https://code.getmdl.io/1.1.3/material.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<section id="center" ng-controller="summonerStats">
<form ng-submit="search()">
<div class="mdl-textfield mdl-js-textfield">
<input class="mdl-textfield__input" type="text" id="summonerName" placeholder="Summoner Name">
<label class="mdl-textfield__label" for="sample1"></label>
</div>
<input class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored" type="submit" value="Search"/>
<p ng-show="show">
{{ mystats.name }}
</p>
</form>
</section>
</body>
</html>
test.js
'use strict';
var lolData = angular.module('lolData', []);
console.log("before controller");
lolData.controller('summonerStats', function($scope, $http) {
var url = "https://restcountries.eu/rest/v1/alpha/co";
console.log("inside controller");
$scope.show = false;
$scope.search = function() {
$http.get(url)
.success(function(response) {
$scope.mystats = response;
$scope.show = true;
console.log("inside success controller");
});
};
});
When I refresh the page the code is executed until "before controller" console.log. It can't get inside lolData.controller. And in the browser console displays the following error.
And html doesn't accept the embeded javascript scope.
What am I missing?
Update 1:
I added the index.html in a codepen: Index.html
And Header.html in a codepen too: header.html
Not sure if this is your problem, but $http.success (and $http.error) has been depreciated since v1.4.4. Instead, use callback functions for success and error
var url = "https://restcountries.eu/rest/v1/alpha/co";
$http.get(url).then(
function successCallback(response) {
$scope.mystats = response;
$scope.show = true;
console.log("inside success controller");
}, function errorCallback(error) {
console.log(error);
});
Your response object doesn't do what you think it does.
From angular's docs you see the response has multiple properties attached to the returned object.
You want
$scope.mystats = JSON.parse(response.data);
I'm learning Angular through a YouTube tutorial series. In the tutorial, you create username and password inputs, and then you use a controller and ngRoute to bring up a dashboard.html page when successful credentials are used. The problem is that when clicking the button, nothing happens, whether the proper credentials are entered or not. Everything is working on the tutorial, and I have triple checked the code thoroughly, and mine looks just like the code in the tutorial. I'm sure I must be missing something though.
What I think:
There is an issue with the click event firing, so maybe there is an issue with how I am calling the function?
The tutorial uses an older angular version (1.3.14), and maybe things have changed? I'm using 1.4.9, but I looked up the api data for the ng-click directive, and all seems well. I also tried using the older version to no avail.
I'm doing something wrong with ngRoute, potentially $scope misuse?
I am inserting all of the code below. Thanks for taking a look!
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Place Title Here</title>
<meta charset = "utf-8"/>
<meta http-equiv="X-UA-compatible" content="IE-edge, chrome=1">
<meta name = "viewport" content = "width = device - width, initial-scale = 1.0"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="controller.js"></script>
</head>
<body ng-app="mainApp">
<div ng-view></div>
</body>
</html>
login.html
<div ng-controller="loginCtrl"></div>
<form action="/" id="myLogin">
Username: <input type="text" id="username" ng-model="username"><br>
Password: <input type="password" id="password" ng-model="password"><br>
<button type="button" ng-click="submit()">Login</button>
</form>
controller.js
var app = angular.module('mainApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'login.html'
})
.when('/dashboard', {
templateUrl: 'dashboard.html'
})
.otherwise({
redirectTo: '/'
});
});
app.controller('loginCtrl', function($scope, $location) {
$scope.submit = function() {
var uname = $scope.username;
var password = $scope.password;
if($scope.username == 'admin' && $scope.password == 'admin') {
$location.path('/dashboard');
}
else {
alert('Nope')
}
};
});
dashboard.html
Welcome User.
Your form needs to be inside the div with ng-controller
<div ng-controller="loginCtrl">
<form action="/" id="myLogin">
Username: <input type="text" id="username" ng-model="username"><br>
Password: <input type="password" id="password" ng-model="password"><br>
<button type="button" ng-click="submit()">Login</button>
</form>
</div>
Otherwise it won't have access to the submit() function.
AngularJS is new to me (and difficult). So I would like to learn how to debug.
Currently I'm following a course and messed something up. Would like to know how to interpret the console error and solve the bug.
plnkr.co code
index.html
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
<h1>{{message}}</h1>
{{ username }}
<form action="searchUser" ng-submit="search(username)">
<input type="search"
required placeholder="Username to find"
ng-model="username"/>
<input type="submit" value="search">
</form>
<div>
<p>Username found: {{user.name + error}}</p>
<img ng-src="http://www.gravatar.com/avatar/{{user.gravatar_id}}" title="{{user.name}}"/>
</div>
</body>
</html>
script.js
(function() {
var app = angular.module("githubViewer", []);
var MainController = function($scope, $http) {
var onUserComplete = function(response) {
$scope.user = response.data;
};
var onError = function(reason) {
$scope.error = "could not fetch data";
};
$scope.search = function(username) {
$http.get("https://api.github.com/users/" + username)
.then(onUserComplete, onError);
};
$scope.username = "angular";
$scope.message = "GitHub Viewer"; };
app.controller("MainController", MainController);
}());
The console only says
searchUser:1 GET http://run.plnkr.co/lZX5It1qGRq2JGHL/searchUser? 404
(Not Found)
Any help would be appreciated.
In your form, action you have written this
<form action="searchUser"
What this does is it will try to submit to a url with currentHostName\searchUser, so in this case your are testing on plunker hence the plunker url.
You can change the url where the form is submitted. Incase you want to search ajax wise then you dont even need to specify the action part. You can let your service/factory make that call for you.
Though not exactly related to debugging this particular error, there is a chrome extension "ng-inspector" which is very useful for angularJS newbies. You can view the value each of your angular variable scopewise and their value. Hope it helps!
Here is the link of the chrome extension: https://chrome.google.com/webstore/detail/ng-inspector-for-angularj/aadgmnobpdmgmigaicncghmmoeflnamj?hl=en
Since you are using ng-submit page is being redirected before the response arrives and you provided any action URL as searchUser which is not a state or any html file so it being used to unknown address, it is async call so it will take some time you can use input types as button instead of submit.
Here is the working plunker.
<!DOCTYPE html>
<html ng-app="githubViewer">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
<h1>{{message}}</h1>
{{ username }}
<form >
<input type="search"
required placeholder="Username to find"
ng-model="username"/>
<input type="button" ng-click="search(username)" value="search">
</form>
<div>
<p>Username found: {{user.name + error}} {{user}}</p>
<img ng-src="http://www.gravatar.com/avatar/{{user.gravatar_id}}" title="{{user.name}}"/>
</div>
</body>
</html>
I am a beginner with MEAN Stack development. I was trying out to play around with some angular stuff but got completely messed up the the controllers.
Here is my main html file
<!--main.html-->
<html>
<head>
<title>Chirp</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="javascripts/chirpApp.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="stylesheets/style.css">
</head>
<body ng-app="chirpApp">
<div id='main' class="container" ng-controller="mainController">
<div class="col-md-offset-2 col-md-8">
<div class="clearfix">
<form ng-Submit="post()">
<input required type="text" class="form-control" placeholder="Your name" ng-model="newPost.created_by" />
<textarea required class="form-control" maxlength="200" rows="3" placeholder="Say something" ng-model="newPost.text"></textarea>
<input class="btn submit-btn pull-right" type="submit" value="Chirp!" />
</form>
<div id="post-stream">
<h4>Chirp Feed</h4>
<div class="post" ng-repeat="post in posts | orderBy:'created_at':true" ng-class-odd="'odd'" ng-class-even="'even'">
<p>{{post.text}}</p>
<small>Posted by #{{post.created_by}}</small>
<small class="pull-right">{{post.created_at | date:"h:mma 'on' MMM d, y"}}</small>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
I have created another html file for registration. here is the code for it.
<!--register.html-->
<html>
<head>
<title>Chirp</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="javascripts/chirpApp.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="stylesheets/style.css">
</head>
<body ng-app="chirpApp">
<div id='main' class="container" ng-controller="authController">
<form class="form-auth" ng-submit="register()">
<h2>Register</h2>
<p class="text-warning">{{error_message}}</p>
<input type="username" ng-model="user.username" placeholder="Username" class="form-control"><br>
<input type="password" ng-model="user.password" placeholder="Password" class="form-control"><br>
<input type="submit" value="Register" class="btn btn-primary" />
</form>
</div>
</body>
</html>
I have created two separate controllers for registration and posts. the first controller works nicely but whenever I am trying to add a second controller I am getting an error message. Here is the code for my controllers.
//chirpApp.js
var app = angular.module('chirpApp', []);
app.controller('mainController', function($scope){
$scope.posts = [];
$scope.newPost = {created_by: '', text: '', created_at: ''};
$scope.post = function(){
$scope.newPost.created_at = Date.now();
$scope.posts.push($scope.newPost);
$scope.newPost = {created_by: '', text: '', created_at: ''};
};
});
app.controller('authController', function($scope){
$scope.user = {username: '', password: ''};
$scope.error_message = '';
$scope.login = function(){
//placeholder until authentication is implemented
$scope.error_message = 'login request for ' + $scope.user.username;
};
$scope.register = function(){
//placeholder until authentication is implemented
$scope.error_message = 'registeration request for ' + $scope.user.username;
};
});
I am getting the following error in the chrome console :
Error: [ng:areq] http://errors.angularjs.org/undefined/ng/areq?p0=authController&p1=not%20a%20function%2C%20got%20undefined
at Error (native)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:6:453
at tb (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:18:250)
at Oa (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:18:337)
at $get (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:61:288)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:48:476
at q (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:7:367)
at S (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:48:342)
at h (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:43:59)
at h (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:43:76)
main.html works fine and the data is being binded successfully.
The issue is with the register.html page. I suppose the authController is not getting binded
Can anyone suggest me the best way of implementing the same? And why the controller is getting undefined?
Try the following checklist:
angularjs lib is included in
ng-app=".." directive is in index.html
..path/to/module and other controllers in index.html
module and controllers defined correctly (spelling, syntax etc)
Controller example (if not using global angular var:
app.controller('AppController', ['$http', '$scope', '$log',
function($http, $scope, $log) {
// TODO: implement
}
]);
Hope this helps.
Here is the plunker of your files
http://embed.plnkr.co/6jNXImBddYqjK23FCWUy/preview
Your application works as expected. Please check your core files is loaded or not.
Hope this helps
your code
When you create a new controller with the AngularJS Controller Sub-Generator you have to reboot Grunt.