Unable to pass form data using Angular.js - javascript

I am new to Angular.js and am trying to send form data to the server but I am getting an error for angular.js:13424 Error: [ng:areq]. I did try many answers available on Stack Overflow but I am not able to find the answer for my problem.
index.view.html (for register)
<div class="col-md-6 col-md-offset-3" >
<input type="text" ng-model="fname" placeholder="Enter the name :"required >Fristname
<br> <br>
button type="button" class="btn btn-success navbar-btn" ng-click=register()>Register </button>
</div>
index.controller.js
(function ()
{
angular
.module('app')
.controller('register.IndexController', function($scope,$http)
{
$scope.register= function()
{
$http.post('http://localhost:9000/user/register', {firstName : $scope.fname}).success(function(response)
{ console.log($scope.fname);
})
}
})
});
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>AngularJS JWT Authentication Example & Tutorial</title>
<!-- bootstrap css -->
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<!-- application css -->
<link href="app-content/app.css" rel="stylesheet" />
</head>
<!-- HEADER AND NAVBAR -->
<header>
<nav class="navbar navbar-default">
<nav class="cf" ng-include="'nav/index.view.html'" ng-controller="Main.IndexController"></nav>
</nav>
</header>

Seems that you are using the wrong controller identifier while processing your request.
You have named your controller as register.IndexController, but from the html , you are trying to access it as Main.IndexController.
Please check whether changing the html controller idenentifier solves your problem.
If you plan on using nested controllers, you can do that also. But the scope has to be identified correctly whichever controller you are using.

Related

Import Json data and show it in angular app

i started learning angular a week ago, and now im trying to construct a app by myself (because people say that is the best way to learn), im trying to do a thing that i didnt before so dont be so rude to me if it is easy, im trying to build a pokedex, im trying to use data that already exist for it in Json, and import it to the controller on angular so i can use ng-repeat to show the data, but i dont know why it doesnt result, maybe im doing a lot of mistakes but i cant find it :/ , i will post what i did here:
Html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="angular.js"></script>
<script src="pokedex.js"></script>
<body ng-app ="pokedex">
<div class="row">
<div class="col-md-offset-1 form-group">
<label for="sel1">Select list:</label>
<select class="form-control">
<option>All</option>
<option>Normal</option>
<option>Watter</option>
<option>Fire</option>
<option>Eletric</option>
<option>Rock</option>
<option>Ice</option>
<option>Grass</option>
<option>Psychic</option>
<option>Poison</option>
<option>Dragon</option>
</select>
</div>
</div>
<div class="row" ng-controller="PokemonController as pokedex">
<div class="col-md-offset-1 col-md-6" ng-repeat = "pokemon in pokedex.pokemons">
<p>Name: {{pokemon.Name}}</p>
</div>
</div>
script
(function(){
var app = angular.module('pokedex',[]);
app.controller('pokemonController',['$http',function($http){
var pokemons = this;
$http.get('https://pokedex-deluxor.rhcloud.com/getall').success(function(data){
pokemons = data;
});
}]);
});
Json Url: Pokedex
Ps: Sorry about my bad english friends :/
ng-repeat = "pokemon in pokedex.pokemons"
you are using ng-repeat on pokedex.pokemons you have to assign data to pokedex.pokemons from controller where you are getting data.
$http.get('https://pokedex-deluxor.rhcloud.com/getall').success(function(data){
// assign data here
});
you should assign the data returned from your http request to the scope object pokemons.
since you used controller as syntax you should do
JS
(function(){
var app = angular.module('pokedex',[]);
app.controller('pokemonController',['$http',function($http){
$http.get('https://pokedex-deluxor.rhcloud.com/getall').success(function(data){
this.pokemons = data;
});
}]);
});
HTML
<div class="row" ng-controller="PokemonController as pokedex">
<div class="col-md-offset-1 col-md-6" ng-repeat = "pokemon in pokedex.pokemons">
<p>Name: {{pokemon.Name}}</p>
</div>

Invalid characters and modules when translating a node.js app from javascript to coffee script

So basically I'm trying to follow the tutorial listed here, except using coffee script instead of javascript. I'm getting two errors on the website, 1. A syntax error regarding the '#' character in the first line of core.coffee (# public/core.coffee) 2. an error that says no module: scotchTodo.
On the actual page, instead of showing the number of todos and each todo, it says
{{ todos.length }} and {{ todo.text }}.
Here's my core.coffee:
# public/core.coffee
scotchTodo = angular.module 'scotchTodo', []
mainController = ($scope, $http) ->
$scope.formData = {}
# when landing on the page, get all todos and show them
$http.get '/api/todos'
.success((data) ->
$scope.todos = data
console.log data
).error((data) ->
console.log 'Error: ' + data
)
# when submitting the add form, send the text to the node API
$scope.createTodo = ->
$http.post '/api/todos', $scope.formData
.success((data) ->
$scope.formData = {} # clear the form so our user is ready to enter another
$scope.todos = data
console.log data
).error((data) ->
console.log 'Error: ' + data
)
# delete a todo after checking it
$scope.deleteTodo = (id) ->
$http.delete '/api/todos/' + id
.success((data) ->
$scope.todos = data
console.log data
).error((data) ->
console.log 'Error: ' + data
)
Here's my index.html:
<!-- index.html -->
<!doctype html>
<!-- ASSIGN OUR ANGULAR MODULE -->
<html ng-app="scotchTodo">
<head>
<!-- META -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><!-- Optimize mobile viewport -->
<title>Todo App</title>
<!-- SCROLLS -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"><!-- load bootstrap -->
<style>
html { overflow-y:scroll; }
body { padding-top:50px; }
#todo-list { margin-bottom:30px; }
</style>
<!-- SPELLS -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script><!-- load jquery -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script><!-- load angular -->
<script src="core.coffee"></script>
</head>
<!-- SET THE CONTROLLER AND GET ALL TODOS -->
<body ng-controller="mainController">
<div class="container">
<!-- HEADER AND TODO COUNT -->
<div class="jumbotron text-center">
<h1>I'm a Todo-aholic <span class="label label-info">{{ todos.length }}</span></h1>
</div>
<!-- TODO LIST -->
<div id="todo-list" class="row">
<div class="col-sm-4 col-sm-offset-4">
<!-- LOOP OVER THE TODOS IN $scope.todos -->
<div class="checkbox" ng-repeat="todo in todos">
<label>
<input type="checkbox" ng-click="deleteTodo(todo._id)"> {{ todo.text }}
</label>
</div>
</div>
</div>
<!-- FORM TO CREATE TODOS -->
<div id="todo-form" class="row">
<div class="col-sm-8 col-sm-offset-2 text-center">
<form>
<div class="form-group">
<!-- BIND THIS VALUE TO formData.text IN ANGULAR -->
<input type="text" class="form-control input-lg text-center" placeholder="I want to buy a puppy that will love me forever" ng-model="formData.text">
</div>
<!-- createToDo() WILL CREATE NEW TODOS -->
<button type="submit" class="btn btn-primary btn-lg" ng-click="createTodo()">Add</button>
</form>
</div>
</div>
</div>
</body>
</html>
Please let me know if you need anything else from me, really trying to understand what's going on. Thanks!
You seem to be trying to use CoffeeScript in the browser:
<script src="core.coffee"></script>
You need to either compile it first, or ad the compiler to your browser code so it can be compiled on the fly. The latter is generally not a good idea, so you should add a build step that uses the CoffeeScript compiler to turn your core.coffee into core.js, then include that script in your index.html.
From the terminal that would look something like coffee -c core.coffee, but there are more options as can be seen here.

how to show error message on submit button?

Can you please tell me how to show an error message on submit button click ?.I am getting an error message after running the program (when I write required :true). I need to show an error message when a user submits the form. I am using this plugin https://github.com/McNull/angular-febworms
Can we get onchange event of select field ?
In my example a red border is displayed when I run the application. I don't want this. I need this when a user clicks the 'submit' button
http://plnkr.co/edit/JOI82JrEBcKJMrzLgtZd?p=preview
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link data-require="bootstrap-css#2.3.2" data-semver="2.3.2" rel="stylesheet" href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" />
<link rel="stylesheet" href="https://rawgithub.com/McNull/angular-febworms/master/package/febworms.min.css" />
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.2.x" src="http://code.angularjs.org/1.2.0/angular.js" data-semver="1.2.0"></script>
<script src="http://code.angularjs.org/1.2.0/angular-route.js"></script>
<script type="text/javascript" src="https://rawgithub.com/McNull/angular-febworms/master/package/febworms.min.js"></script>
<script type="text/javascript" src="dummy-schema.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MyFormController as frmCtrl">
<div class="container">
<div class="row-fluid">
<form class="form-horizontal" name="form.state" novalidate>
<div febworms-form
febworms-schema="form.schema"
febworms-form-data="form.data">
</div>
<div class="form-actions">
<a class="btn btn-primary" ng-disabled="form.state.$invalid" ng-click="frmCtrl.save()">Save changes</a>
</div>
</form>
</div>
</div>
</body>
</html>
But need to blur event to validate or onchange event ?
Since your form name is 'form.state' and your field name is 'required' (which is a bit confusing by the way, you may want to change that), you can get useful information about your validation state with the following expressions in the scope of your form:
form.state.required.$error // yields something like { "required": true, "pattern": false }
form.state.required.$valid // yields a boolean
form.state.$error
form.state.$valid
I haven't heard of a way of knowing whether a form has already been submitted or not. My best shot would be to add some state for this in the controller :
$scope.errorShown = false;
$scope.showErrorMessage = function(){
$scope.errorShown = true;
};
And in your HTML :
<div class="form-actions">
<a class="btn btn-primary" ng-disabled="form.state.$invalid" ng-click="(form.state.$valid ? frmCtrl.save() : showErrorMessage())">Save changes</a>
</div>
<div ng-if="errorShown && form.state.$invalid">
Your form is not valid.
</div>
Plunkr here.

Restify server with Angular, not working

I am learning to use Restify to build a Restful API and work with Angular.
Below is my structure:
Project
page_admin
core.js
index.html
node_modules
restify
mongojs
server.js
I had set up server and implemented several API calls.
Below news API return a list of JSON data in browser:
`http://localhost:8080/news`
`[{"_id":"53b2a2c3373551813dfe8b91","title":"first","subtitle":"foobar","textbody":"","postedOn":"2014-07-01T12:00:03.215Z"},{"_id":"53b2a122373551813dfe8b8e","title":"my second","subtitle":"my second title","textbody":"node is cool","postedOn":"2014-07-01T11:53:06.389Z"},{"_id":"53b2a0cd373551813dfe8b8d","title":"delay announcement","subtitle":"sub ","textbody":"I am the text body","postedOn":"2014-07-01T11:51:41.678Z"}]`
here is my code to handle client side route:
server.get('/', restify.serveStatic({
'directory': './page_admin',
'default': 'index.html'
}));
My index.html is simple:
<!-- index.html -->
<!doctype html>
<!-- ASSIGN OUR ANGULAR MODULE -->
<html ng-app="bluesky">
<head>
<!-- META -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><!-- Optimize mobile viewport -->
<title>My test app</title>
<!-- SCROLLS -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"><!-- load bootstrap -->
<style>
html { overflow-y:scroll; }
body { padding-top:50px; }
#todo-list { margin-bottom:30px; }
</style>
<!-- SPELLS -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script><!-- load jquery -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script><!-- load angular -->
<script src="core.js"></script>
</head>
<!-- SET THE CONTROLLER AND GET ALL TODOS -->
<body ng-controller="mainController">
<div class="container">
<!-- HEADER AND TODO COUNT -->
<div class="jumbotron text-center">
<h1>My example is working <span class="label label-info">{{ news.length }}</span></h1>
</div>
<!-- TODO LIST -->
<div id="todo-list" class="row">
<div class="col-sm-4 col-sm-offset-4">
<!-- LOOP OVER THE TODOS IN $scope.todos -->
<div class="checkbox" ng-repeat="new in news">
<label>
<input type="checkbox" ng-click="deleteTodo(new._id)"> {{ new.subtitle }}
</label>
</div>
</div>
</div>
</div>
</body>
</html>
core.js is like this:
var bluesky = angular.module('bluesky', []);
function mainController($scope, $http) {
$scope.formData = {};
$http.get('/news')
.success(function(data) {
$scope.news = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
}
when I try to navigate to: http://localhost:8080
I got my index page but it shows me:
'My example is working {{ news.length }}
and in console, I saw following error:
GET `http://localhost:8080/core.js` 404 (Not Found)
localhost/:24
Uncaught Error: No module: bluesky
angular.min.js:18
what I just missed so that the angular is not retrieving the data?
=============================================================
upate
if I directly include core.js put code inside , then it works.
but, how to solve this 404 not found issue? just don't want to include all js files in the index page.
As far as my knowledge about angular js, controller is not defined in your module. So instead of using function mainController($scope, $http) {
....
}
you should define controller inside the module bluesky as follows
bluesky.controller("mainController",function($scope,$http)
{
....
});

Using ng-switch to swap templates

I'm trying to switch a "sign in" form for a "sign up" form whenever the user clicks on the "Sign Up" button in my angular app, but at the moment nothing is happening when the button is clicked; The sign in form remains on the screen and there are no console errors. Can anyone tell me where I'm going wrong?
I'm attempting to do this purely in html, is this even possible to achieve?
EDIT: I included a signup function in my UserCtrl which takes care of signing in/ out. Now when I click on sign up the alert is trigger but I get a console error saying TypeError: boolean is not a function.
$scope.signup = function() {
alert('signup function hit');
$scope.signup = true;
}
EDIT 2:
<!DOCTYPE html>
<html ng-app="myApp" >
<head>
<title> My App</title>
<link rel="stylesheet" type="text/css" href="css/app.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" type="text/css" href="css/signin.css">
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet"/>
</head>
<body ng-controller="MainCtrl">
<div ng-switch on="view.name">
<div ng-switch-default ng-controller="UserCtrl">
<div ng-show="!isAuthenticated">
<form class = "form-signin">
<div class="control-group">
<img src="img/logo.png">
<br />
<div class="controls">
<br />
<input type="text" ng-model="username" placeholder = "Email Address" >
</div>
<br />
<div class="controls">
<input type="password" ng-model="password" placeholder = "Password" >
</div>
<div class="controls">
<button class = "btn btn-default" ng-click="signIn()">Sign In</button>
<button class = "btn btn-primary" ng-click="view.name = 'signup'">Register</button>
</div>
</div>
</form>
</div>
<div ng-switch-when="signup" ng-controller = "UserNewCtrl" >
<label>
This is where my form should be when my signup button is clicked.
</label>
</div>
//This part of index.html is only shown when a user has been authenticated
<div ng-show="isAuthenticated">
<div class="col-md-2">
//MenuBar code is here
</div>
//Other templates get loaded here
<div class="col-md-10">
<div ng-view></div>
</div>
</div>
</div>
<script src="js/vendor.js"></script>
<script src="js/app.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery-1.10.2.js"></script>
<script src="js/transition.js"></script>
<script src="js/ui-utils.js"></script>
</div>
</body>
</html>
MainCtrl.js:
angular.module('myApp.controllers')
.controller('MainCtrl', function($scope) {
$scope.view={
name: ''
};
})
To achieve your requirement you need a wrapper controller that hold ng-switch on model because ngSwitch creates child scope.
You can design your view like
<body ng-controller="mainCtrl">
<div ng-switch on="view.name">
<div ng-switch-default ng-controller="signInCtrl">
<h1>this is sign in page</h1>
sign in
<br>
go to sign up page
</div>
<div ng-switch-when="signup" ng-controller="signUpCtrl">
<h1>this is sign up page</h1>
sign up
<br>
go to sign in page
</div>
</div>
</body>
Here mainCtrl holds view.name and by default ng-switch-default works means your sign in page, then when you click
go to sign up page
view.name model changed and your sign-up page appear.
Check the Demo
move the app controller to the html tag, then the directive in your body tag should read if you want to match an expression
<html ng-app="myApp">
<body ng-switch="signup">
see here
where signup is a boolean in your myApp scope, that will presumably be changed when the signIn criteria is satisfactory
$rootScope.signup = true;
you can also achieve similar with the ng-show and ng-hide directives

Categories

Resources