I am developing Spring MVC AngularJS example. I've simply taken a code from link: https://github.com/sivaprasadreddy/sivalabs-blog-samples-code/tree/master/springmvc-angular-crud. I am able to login using siva#gmail.com/siva successfully, but when I'm accessing logout, user profile, setting etc, nothing is happening. Please guide what is missing here.
login.jsp:
<!DOCTYPE html>
<%#include file="taglib.jsp" %>
<html>
<head>
<title>Login</title>
<base href="${rootUrl}">
<%# include file="assets.jspf" %>
</head>
<body>
<div class="col-md-6 col-md-offset-2">
<c:if test="${param.error != null}">
<div class="alert alert-danger">
Invalid UserName and Password.
</div>
</c:if>
<c:if test="${param.logout != null}">
<div class="alert alert-success">
You have been logged out.
</div>
</c:if>
</div>
<div class="row">
<div class="col-md-6 col-md-offset-2">
<h2>User Login Form</h2>
<form:form id="loginForm" method="post" action="login" modelAttribute="user"
class="form-horizontal" role="form" cssStyle="width: 800px; margin: 0 auto;">
<div class="form-group">
<label for="username" class="col-sm-2 control-label">UserName*</label>
<div class="col-sm-4">
<input type="text" id="username" name="username" class="form-control" placeholder="UserName" />
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">Password*</label>
<div class="col-sm-4">
<input type="password" id="password" name="password" class="form-control" placeholder="Password" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-4">
<input type="submit" class="btn btn-primary" value="Login">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-4">
New User? Register
</div>
</div>
</form:form>
</div>
</div>
</body>
</html>
register.jsp
<!DOCTYPE html>
<%#include file="taglib.jsp"%>
<html>
<head>
<title>Create User</title>
<script type="text/javascript">
$(document).ready(function() {
$("#registrationForm").submit(function( event ) {
var userName = $.trim($("#userName").val());
var password = $.trim($("#password").val());
var firstName = $.trim($("#firstName").val());
var email = $.trim($("#email").val());
if(userName == '' || password == '' || firstName == '' || email == ''){
alert("Please enter all mandatory fields");
event.preventDefault();
return false;
}
});
});
</script>
</head>
<body>
<div class="col-md-6 col-md-offset-2">
<c:if test="${ERROR != null }">
<div class="alert alert-danger">
<p>${ERROR}
</div>
</c:if>
</div>
<div class="row">
<div class="col-md-6 col-md-offset-2">
<h2>User Registration Form</h2>
<form:form id="registrationForm" method="post" action="register"
modelAttribute="user" cssStyle="width: 800px; margin: 0 auto;"
class="form-horizontal" role="form">
<div class="form-group">
<label for="userName" class="col-sm-2 control-label">UserName*</label>
<div class="col-sm-4">
<input type="text" id="userName" name="userName"
class="form-control" placeholder="UserName" />
<form:errors path="userName" />
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">Password*</label>
<div class="col-sm-4">
<input type="password" id="password" name="password"
class="form-control" placeholder="Password" />
<form:errors path="password" />
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email*</label>
<div class="col-sm-4">
<input type="text" id="email" name="email" class="form-control"
placeholder="Email" />
<form:errors path="email" />
</div>
</div>
<div class="form-group">
<label for="firstName" class="col-sm-2 control-label">FirstName*</label>
<div class="col-sm-4">
<input type="text" id="firstName" name="firstName"
class="form-control" placeholder="FirstName" />
<form:errors path="firstName" />
</div>
</div>
<div class="form-group">
<label for="lastName" class="col-sm-2 control-label">LastName</label>
<div class="col-sm-4">
<input type="text" id="lastName" name="lastName"
class="form-control" placeholder="LastName" />
<form:errors path="lastName" />
</div>
</div>
<div class="form-group">
<label for="dob" class="col-sm-2 control-label">Date Of
Birth</label>
<div class="col-sm-4">
<input type="text" id="dob" name="dob" class="form-control"
placeholder="dd-MM-yyyy" />
<form:errors path="dob" cssClass="text-danger" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-4">
<input type="submit" class="btn btn-primary" value="Register">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-4">
Already Registered? Login
</div>
</div>
</form:form>
</div>
</div>
</body>
</html>
welcome.jsp:
<!DOCTYPE html>
<%# include file="taglib.jsp" %>
<html lang="en" ng-app="usersApp">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Spring MVC Angular Tutorials : Forum</title>
<%# include file="assets.jspf"%>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse"
data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span> <span
class="icon-bar"></span> <span class="icon-bar"></span> <span
class="icon-bar"></span>
</button>
<a class="navbar-brand" href="${rootUrl}home">My DashBoard</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li class="dropdown"><a class="dropdown-toggle"
data-toggle="dropdown" href="#"> My Account </a>
<ul class="dropdown-menu dropdown-user">
<li><a href="${rootUrl}myAccount"><i
class="fa fa-user fa-fw"></i> User Profile</a></li>
<li><a href="${rootUrl}changePwd"><i
class="fa fa-gear fa-fw"></i> Settings</a></li>
<li class="divider"></li>
<li>Logout</li>
</ul> <!-- /.dropdown-user --></li>
<li>Logout</li>
</ul>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-3 sidebar">
<div class="list-group">
<span class="list-group-item active">Personal Data</span> PhoneBook Events <span
class="list-group-item active">Settings</span> <a href="#"
class="list-group-item">Configuration</a>
</div>
</div>
<div class="col-md-9 " ng-controller="UserCtrl">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th width="20px;">Id</th>
<th width="100px;">FirstName</th>
<th width="100px;">LastName</th>
<th width="150px;">Email</th>
<th width="100px;">Edit / Delete</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in userList">
<td>{{user.id}}</td>
<td>{{user.firstName}}</td>
<td>{{user.lastName}}</td>
<td>{{user.email}}</td>
<td><span style="cursor: pointer;"
class="glyphicon glyphicon-pencil"
ng-click="handleEditUser(user)"></span> <span
style="cursor: pointer;" class="glyphicon glyphicon-trash"
ng-click="handleDeleteUser(user)"></span></td>
</tr>
</tbody>
</table>
<div class="panel panel-default">
<div class="panel-heading">Edit User</div>
<div class="panel-body">
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="inputId" class="col-sm-2 control-label">Id</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputId"
placeholder="Id" ng-model="editUser.id">
</div>
</div>
<div class="form-group">
<label for="inputFirstName" class="col-sm-2 control-label">FirstName</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputFirstName"
placeholder="FirstName" ng-model="editUser.firstName">
</div>
</div>
<div class="form-group">
<label for="inputLastName" class="col-sm-2 control-label">LastName</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputLastName"
placeholder="LastName" ng-model="editUser.lastName">
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="inputEmail"
placeholder="Email" ng-model="editUser.email">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default"
ng-click="handleUpdateUser(editUser)">Save</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
ContactController.java
#RestController
#RequestMapping("/users/{userId}/contacts/")
public class ContactController{
#Autowired
private UserService userService;
#RequestMapping(value="", method=RequestMethod.GET)
public List<Contact> findAll(#PathVariable("userId") int userId) {
return userService.findUserContacts(userId);
}
#RequestMapping(value="/{contactId}", method=RequestMethod.GET)
public Contact findContact(#PathVariable("userId") int userId, #PathVariable("contactId") int contactId) {
return userService.findUserContact(userId, contactId);
}
#RequestMapping(value="", method=RequestMethod.POST)
public Contact createContact(#PathVariable("userId") int userId, Contact contact) {
return userService.saveUserContact(contact);
}
#RequestMapping(value="", method=RequestMethod.PUT)
public Contact updateContact(#PathVariable("userId") int userId, Contact contact) {
return userService.saveUserContact(contact);
}
#RequestMapping(value="/{contactId}", method=RequestMethod.DELETE)
public void deleteContact(#PathVariable("userId") int userId, #PathVariable("contactId") int contactId) {
userService.deleteUserContact(userId, contactId);
}
}
UserController.java
#Controller
public class UserController {
#Autowired
private UserService userService;
#RequestMapping(value = "login", method = RequestMethod.GET)
public String loginForm(Model model){
model.addAttribute("user", new User());
return "login";
}
#RequestMapping(value = "/register", method = RequestMethod.GET)
public String registrationForm(Model model){
model.addAttribute("user", new User());
return "register";
}
#RequestMapping(value = "/register", method = RequestMethod.POST)
public String handleRegistration(#ModelAttribute("user") User user, BindingResult errors, Model model){
if (errors.hasErrors()) {
return "register";
}
try {
userService.createUser(user);
return "redirect:login";
} catch (Exception e) {
e.printStackTrace();
model.addAttribute("ERROR", e.getMessage());
return "register";
}
}
}
assets.jspf
<script type="text/javascript" src="${rootUrl}resources/jquery/jquery-1.10.2.js"></script>
<link rel="stylesheet" href="${rootUrl}resources/bootstrap/css/bootstrap.min.css"/>
<link rel="stylesheet" href="${rootUrl}resources/bootstrap/css/bootstrap-theme.min.css"/>
<script type="text/javascript" src="${rootUrl}resources/bootstrap/js/bootstrap.min.js"></script>
<script src="resources/angularjs/angular.js"></script>
<script src="resources/angularjs/angular-resource.js"></script>
<script src="${rootUrl}resources/js/controllers.js"></script>
<script src="${rootUrl}resources/js/services.js"></script>
<link rel="stylesheet" href="${rootUrl}resources/css/styles.css"/>
<script type="text/javascript" src="${rootUrl}resources/js/app.js"></script>
taglib.jsp:
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%# taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<c:url var="rootUrl" value="/"/>
Please let me know if You need any info.
Screen shots of UI:
If I call any tab it gives nothing why?
not seeing any handelar for /logout. Create a controller method to handle this request
#RequestMapping(value = "/logout", method = RequestMethod.GET/POST)
public String registrationForm(Model model){
//your logic
return "register";
//or return "redirect:/login"
}
Related
This is the form.
<div class="row" ng-controller="contactsCtrl">
<form ng-show="addFormShow">
<h3>Add Contact</h3>
<!-- Add form -->
<div class="row">
<div class="large-6 columns">
<label>Name:
<input type="text" ng-model="name" placeholder="Contact Name" required />
</label>
</div>
<div class="large-6 columns">
<label>Email:
<input type="text" ng-model="email" placeholder="Contact Email" required />
</label>
</div>
</div>
<div class="row">
<div class="large-6 columns">
<label>Company:
<input type="text" ng-model="company" placeholder="Company Name" required />
</label>
</div>
<div class="large-6 columns">
<label>Work Phone:
<input type="text" ng-model="work_phone" placeholder="Work Phone" required />
</label>
</div>
</div>
<div class="row">
<div class="large-6 columns">
<label>Mobile Phone:
<input type="text" ng-model="mobile_phone" placeholder="Mobile Phone" required />
</label>
</div>
<div class="large-6 columns">
<label>Home Phone:
<input type="text" ng-model="home_phone" placeholder="Home Phone" required />
</label>
</div>
</div>
<div class="row">
<div class="large-6 columns">
<label>Street Address:
<input type="text" ng-model="street_address" placeholder="Street Address" required />
</label>
</div>
<div class="large-6 columns">
<label>City:
<input type="text" ng-model="city" placeholder="City" required />
</label>
</div>
</div>
<div class="row">
<div class="large-6 columns">
<label>State:
<input type="text" ng-model="state" placeholder="State" required />
</label>
</div>
<div class="large-6 columns">
<label>Zip Code:
<input type="text" ng-model="zipcode" placeholder="Zip Code" required />
</label>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<input type="submit" value="Add Contact" class="button" />
</div>
</div>
</form>
<div class="large-10 columns">
<h3>Your Contacts (3)</h3>
<table>
<thead>
<tr>
<th width="200px">Name</th>
<th width="200px">Company</th>
<th width="25%">Email</th>
<th width="25%">Actions</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="contact in contacts">
<td>{{contact.name}}</td>
<td>{{contact.company}}</td>
<td>{{contact.email}}</td>
<td><a class="button tiny" ng-click="showEditForm(contact)">Edit</a>
<a class="button tiny alert" ng-click="removeContact(contact)">Delete</a></td>
</tr>
</tbody>
</table>
</div>
<div class="small-12 large-2 columns">
<a class="button large" ng-click="showAddForm()">+</a>
</div>
</div>
This is the controller.
'use strict';
angular.module('myContacts.contacts', ['ngRoute','firebase'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/contacts', {
templateUrl: 'contacts/contacts.html',
controller: 'contactsCtrl'
});
}])
.controller('contactsCtrl', ['$scope', '$firebaseArray', function($scope,$firebaseArray) {
var ref = new Firebase('https://mycontacts-1bb2d.firebaseio.com/contacts');
$scope.contacts = $firebaseArray(ref);
$scope.showAddForm = function(){
$scope.addFormShow = true;
}
}]);
This is pretty simple code. Its supposed to show the form when the user clicks on the '+' button. But I cant figure out why the ng-show directive is not working.
It works fine with your code, check if you have properly added ng-controller in your code.
DEMO
var myApp = angular.module('ReqWebApp', [])
myApp.controller('contactsCtrl', function contactsCtrl($scope) {
$scope.showAddForm = function(){
$scope.addFormShow = true;
}
});
<!DOCTYPE html>
<html ng-app="ReqWebApp">
<head>
<meta charset="UTF-8">
<title>New Request</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="contactsCtrl">
<form ng-show="addFormShow">
<h3>Add Contact</h3>
<!-- Add form -->
<div class="row">
<div class="large-6 columns">
<label>Name:
<input type="text" ng-model="name" placeholder="Contact Name" required />
</label>
</div>
<div class="large-6 columns">
<label>Email:
<input type="text" ng-model="email" placeholder="Contact Email" required />
</label>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<input type="submit" value="Add Contact" class="button" />
</div>
</div>
</form>
<div class="small-12 large-2 columns">
<a class="button large" ng-click="showAddForm()">+</a>
</div>
</body>
</html>
The code works fine for me. I think you might have done some small error in adding controller. Refer the code below
<html ng-app='FormApp'>
<head>
</head>
<body ng-controller='contactsCtrl'>
<form ng-show="addFormShow">
<h3>Add Contact</h3>
<!-- Add form -->
<div class="row">
<div class="large-6 columns">
<label>Name:
<input type="text" ng-model="name" placeholder="Contact Name" required />
</label>
</div>
<div class="large-6 columns">
<label>Email:
<input type="text" ng-model="email" placeholder="Contact Email" required />
</label>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<input type="submit" value="Add Contact" class="button" />
</div>
</div>
</form>
<div class="small-12 large-2 columns">
<a class="button large" ng-click="showAddForm()">+</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>
<script>
angular.module('FormApp', []).controller('contactsCtrl', ['$scope', function($scope) {
$scope.showAddForm = function() {
$scope.addFormShow = true;
}
}]);
</script>
</body>
</html>
I need one example for validations on dynamic added fields. Here is my page.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script
src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js">
</script>
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js">
</script>
<title>Add Remove in AngularJS</title>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.deleted = [];
$scope.inputs = [];
$scope.addRow = function(){
$scope.inputs.push({name:'', age:''});
};
$scope.removeRow = function(index, input){
// alert(index);
// alert(input);
$scope.deleted.push(input);
$scope.inputs.splice(index,1);
};
});
</script>
</head>
<body style="background-color: gray; margin-top: 10px; ">
<center>
<div class="row" ng-app="myApp" ng-controller="myCtrl">
<div class="col-md-6">
<div class="panel panel-flat">
<div class="panel-header">
<h4>
Person Address
<button ng-click="addRow()">Add</button>
</h4>
</div>
<div class="panel-body">
<form name="form" class="form-horizontal">
<div ng-repeat="input in inputs">
<div class="form-group" ng-class="{'has-error' : form.name.$invalid}">
<label class="col-md-2 control-label">Name</label>
<div class="col-md-10">
<input type="text" ng-model="input.name" name="name[$index]" ng-maxlength="45" ng-minlength="3"
class="form-control" ng-pattern="/^[a-zA-Z]+$/" required />
<span class="help-block" ng-show="form.name[$index].$error.pattern">Alphabet only</span>
<span class="help-block" ng-show="form.name[$index].$error.minlength">Too Short</span>
<span class="help-block" ng-show="form.name[$index].$error.maxlength">Too Long</span>
<span class="help-block" ng-show="form.name[$index].$error.required">required</span>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Age</label>
<div class="col-md-10">
<input type="text" ng-model="input.age" name="age"
class="form-control" ng-pattern="/^[0-9]{0,3}$/" /><br>
<span ng-show="form.age.$invalid && form.age.$error.pattern">Number
length should be 3</span>
</div>
</div>
<button ng-click="removeRow($index, input)">Remove</button>
<hr>
</div>
</form>
</div>
</div>
</div>
<!-- inputs :{{inputs}}<br>deleted : {{deleted}} -->
</div>
</center>
</body>
</html>
You can add a fonction to you controller :
app.controller('myCtrl', function($scope) {
//...
$scope.validationFn = function () {
//do you validation here
};
then you just need to modify
<form name="form" class="form-horizontal" ng-submit="validationFn()">
Here is the answer:
<div class="panel-body"><form name="form" class="form-horizontal">
<div ng-repeat="input in inputs"><ng-form name="sfIn"><div class="form-group" >
<label class="col-md-2 control-label">Name</label>
<div class="col-md-10">
<input type="text" ng-model="input.name" name="name" ng-maxlength="45" ng-minlength="3"
class="form-control" ng-pattern="/^[a-zA-Z]+$/" required />
<span
class="help-block" ng-show="sfIn.name.$error.pattern">Alphabet only</span>
<span
class="help-block" ng-show="sfIn.name.$error.minlength">Too Short</span>
<span
class="help-block" ng-show="sfIn.name.$error.maxlength">Too Long</span>
<span
class="help-block" ng-show="sfIn.name.$touched.required || sfIn.name.$error.required ||
sfIn.name.$dirty.required">required</span>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Age</label>
<div class="col-md-10">
<input type="text" ng-model="input.age" name="age"
class="form-control" ng-pattern="/^[0-9]{0,3}$/" /><br>
<span
ng-show="sfIn.age.$error.pattern">Number
length should be 3</span>
</div>
</div>
<button
ng-click="removeRow($index, input)">Remove</button>
</ng-form>
<hr>
</div>
</form>
</div>
I am using the following angularJS function to upload images to my site,
.controller('fupController', ['$scope', '$http', function ($scope, $http) {
var formdata = new FormData();
$scope.getTheFiles = function ($files) {
$scope.imagesrc = [];
for (var i = 0; i < $files.length; i++) {
var reader = new FileReader();
reader.fileName = $files[i].name;
reader.onload = function (event) {
var image = {};
image.Name = event.target.fileName;
image.Size = (event.total / 1024).toFixed(2);
image.Src = event.target.result;
$scope.imagesrc.push(image);
$scope.$apply();
}
reader.readAsDataURL($files[i]);
}
angular.forEach($files, function (value, key) {
formdata.append(key, value);
})
}
$scope.uploadFiles = function () {
var request = {
method: 'POST',
url: 'http://localhost:61194/api/FileUpload',
//data: formdata,
//data: { gallery: $scope.galleries[$scope.index].Id },
file: File,
headers: {
'Content-Type': undefined
}
};
$http(request).success(function (d) {
alert(d);
$scope.reset();
}).error(function () {
alert("Failed");
$scope.reset();
})
}
$scope.reset = function () {
angular.forEach(
angular.element("input [type = 'file']"),
function (inputElem) {
angular.element(inputElem).val(null);
}
);
$scope.imagesrc = [];
formdata = new FormData();
}
}])
the full code of the angular html template is as below:
<section class="view">
<div class="form-group">
<div class="controls">
<button type="submit" class="btn btn-success" ng-click="goBack()">Back</button>
</div>
</div>
<div class="row">
<img class="contact-img" ng-src="{{contact.imageUrl}}">
<section>
<article>
<div class="contact-card">
<h3 class="text-center">{{contact.firstName}} {{contact.lastName}}</h3>
<h6 class="text-center">{{contact.emailAddress}}</h6>
</div>
</article>
</section>
</div>
<form class="form margin-top-small" name="contactForm">
<fieldset>
<legend>Contact</legend>
<div class="form-group">
<label class="control-label" for="first-name">Picture</label>
<div class="controls">
<!--<input type="text" class="form-control input-large" required id="Picture" placeholder="Enter image Url" onchange="angular.element(this).scope().uploadFile(this.files)" ng-model="contact.imageUrl">-->
<!--<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this)" />-->
<!--<div ng-controller="fupController">
<input type="button" class="btn btn-success" ng-click="uploadFiles()" value="Upload" />
</div>-->
<div ng-controller="fupController">
<div class="container">
<div class="panel panel-info">
<div class="panel-heading">
Photos
</div>
<div class="panel-body">
<table class="table table-hover table-bordered">
<thead>
<tr>
<td>title</td>
<td>Image</td>
<td>Size</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="image in imagesrc track by $index">
<td>{{image.Name}}</td>
<td>
<img ng-src="{{image.Src}}" title="{{image.Title}}" style="width: 100px;" />
</td>
<td>{{image.Size}}</td>
</tr>
</tbody>
</table>
<div class="row">
<div class="col-lg-7">
<input type="file" multipe ng-files="getTheFiles($files)" />
</div>
<div class="col-lg-5">
<input ng-disabled="!imagesrc.length" type="button" class="btn btn-success" ng-click="uploadFiles()" value="Upload" />
<input ng-disabled="!imagesrc.length" type="button" class="btn btn-success" ng-click="reset()" value="Cancel" />
</div>
</div>
</div>
</div>
</div>
</div>
<!--<input type="file" file-model="myFile" />
<button ng-click="uploadFile()">upload me</button>
<!-- FILE UPLOAD WITH PREVIEW, NEED TO ENABLE THE JAVASCRIPT BELOW -->
<!--<input type="file" id="imagess" onchange="previewFile()" ng-model="contact.imageUrl"><br>-->
<!--FILE UPLOAD 1-->
<!--<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)" />-->
<!--FILE UPLOAD 2-->
<!--<div ng-controller="MyCtrl">
<input type="file" ngf-select="onFileSelect($files)" multiple>
</div>-->
<!--FILE UPLOAD 3-->
<!--<div ng-controller="fileuploadCtrl">
<input type="file" ng-file-select name="file" ng-file-change="upload($files)">
<div class="progress" style=" margin 0%">
<div class="progress-bar" role="progressbar" ng-style="{ 'width': percentComplete + '%' }" style="width: 0%;">
<span ng-if="percentComplete === 100">{{items.attachment}} upload completed successfully</span>
</div>
<span ng-if="percentComplete > 0" class="fileupload">{{percentComplete}}%</span>
</div>
</div>-->
<!--FILE UPLOAD 4-->
<!--<div ng-controller="fileuploadCtrl">
<input type="file" ngf-select="upload($files)" multiple>
</div>-->
<!--FILE UPLOAD 5-->
<!--<div ng-controller="MyCtrl2">
<h4>Upload on file select</h4>
<button type="file" ngf-select="uploadFiles($file, $invalidFiles)"
accept="image/*" ngf-max-height="1000" ngf-max-size="1MB">
Select File
</button>
<br><br>
File:
<div style="font:smaller">
{{f.name}} {{errFile.name}} {{errFile.$error}} {{errFile.$errorParam}}
<span class="progress" ng-show="f.progress >= 0">
<div style="width:{{f.progress}}%"
ng-bind="f.progress + '%'"></div>
</span>
</div>
{{errorMsg}}
</div>-->
<!--FILE UPLOAD 6-->
<!--<div ng-controller="MyCtrl2">
<input type="file" ngf-select="uploadFiles($file, $invalidFiles)" multiple>
</div>-->
<!--<img src="" height="200" alt="Image preview...">-->
<!--<input type="file" id="multi_file_upload" ng-model="contact.imageUrl"><br>
<img src="" height="200" alt="Image preview...">-->
</div>
</div>
<div class="form-group">
<label class="control-label" for="first-name">First Name</label>
<div class="controls">
<input type="text" class="form-control input-large" required id="first-name" placeholder="Enter first name" ng-model="contact.firstName">
</div>
</div>
<div class="form-group">
<label class="control-label" for="last-name">Last Name</label>
<div class="controls">
<input type="text" class="form-control input-large" required id="last-name" placeholder="Enter last name" ng-model="contact.lastName">
</div>
</div>
<div class="form-group">
<label class="control-label" for="email-address">Email</label>
<div class="controls">
<input type="text" class="form-control input-large" required ng-pattern="{{regularExpressions.emailAddress}}" id="email-address" placeholder="Enter email address" ng-model="contact.emailAddress">
</div>
</div>
<div class="form-group margin-top-small">
<div class="controls">
<!--<button type="submit" class="btn btn-lg btn-primary" ng-click="save(contact, contactForm)">Save Contact</button>-->
<button type="submit" class="btn btn-lg btn-primary" ng-click="save(contact, contactForm)">Save Contact</button>
<span class="alert alert-info" ng-show="hasSaved">
<strong>Confirmation: </strong>contact saved ! <br>
<button type="button" class="close" data-dismiss="alert">×</button>
</span>
<span class="alert alert-info" ng-show="saveError">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Failed: </strong>contact not saved ! <br>
</span>
<p>{{errortext}}</p>
</div>
</div>
</fieldset>
</form>
This is the Index page and the scripts:
<!DOCTYPE html>
<html data-ng-app="app">
<head>
<title>CSS Black Book</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<link href="lib/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="src/css/app.css" rel="stylesheet" media="screen">
<link href="src/css/Flip.css" rel="stylesheet" media="screen">
</head>
<body>
<header data-ng-controller="HeaderController">
<nav class="navbar">
<a class="navbar-brand" href="#/contacts">CSS Black Book</a>
<ul class="nav navbar-nav">
<li ng-class="{active: routeIs('contacts')}">Contacts</li>
<li ng-class="{active: routeIs('about')}">About</li>
</ul>
</nav>
</header>
<div data-ng-view data-ng-animate="{enter: 'view-enter', leave: 'view-leave'}"></div>
<script src="lib/jquery/jquery.min.js"></script>
<script src="lib/bootstrap/js/bootstrap.min.js"></script>
<!--<script src="lib/angular/ng-file-upload-shim.min.js"></script>--> <!-- for no html5 browsers support -->
<script src="../node_modules/ng-file-upload/dist/ng-file-upload-shim.min.js"></script>
<!--<script src="../../Scripts/angular.js"></script>-->
<script src="lib/angular/angular.min.js"></script>
<!--<script src="lib/angular/ng-file-upload.min.js"></script>-->
<script src="../node_modules/ng-file-upload/dist/ng-file-upload.min.js"></script>
<script src="lib/angular/angular.resource.min.js"></script>
<!--<script src="../Scripts/angular-resource.js"></script>-->
<script src="src/common/resources/contacts.js"></script>
<script src="src/common/resources/lookups.js"></script>
<script src="src/common/services/config.js"></script>
<script src="src/common/services/state.js"></script>
<script src="src/common/directives/mouse-enter-css.js"></script>
<script src="src/common/directives/mouse-leave-css.js"></script>
<script src="src/common/services/config.js"></script>
<script src="src/app/contacts/contacts.js"></script>
<script src="src/app/about/about.js"></script>
<script src="src/app/app.js"></script>
<script src="lib/respond/respond.min.js"></script>
<!--<script src="../../Scripts/angular.js"></script>-->
<!--<script src="../../site/lib/jquery/jquery.min.js"></script>-->
<!--<script src="../../site/lib/bootstrap/js/bootstrap.min.js"></script>-->
<!--<script src="../App2/file-upload.js"></script>-->
</body>
</html>
Here is the controller that gets called to do the actual upload of the image to a project folder called "Gallery":
public class FileUploadController : ApiController
{
private FileUploadDemoDbContext Context = new FileUploadDemoDbContext();
[System.Web.Http.HttpPost]
[HttpRoute("api/FileUpload")]
public IHttpActionResult Upload()
{
int uploadCount = 0;
string sPath = System.Web.Hosting.HostingEnvironment.MapPath("/Gallery/");
System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
for (int i = 0; i < files.Count; i++)
{
System.Web.HttpPostedFile file = files[i];
string fileName = new FileInfo(file.FileName).Name;
if (file.ContentLength > 0)
{
//Guid id = new Guid();
Guid id = Guid.NewGuid();
string modifiedFileName = id.ToString() + "_" + fileName;
if (!File.Exists(sPath + Path.GetFileName(modifiedFileName)))
{
file.SaveAs(sPath + Path.GetFileName(modifiedFileName));
uploadCount++;
//Context.Galleries.Add(new Gallery() { Id = Convert.ToInt32(id.ToString()), FileName = "/Gallery" + modifiedFileName, Title = fileName });
Context.Galleries.Add(new Gallery() { Id = id, FileName = "/Gallery" + modifiedFileName, Title = fileName });
}
}
}
if (uploadCount > 0)
{
Context.SaveChanges();
return Ok("Uploaded Successfully");
}
return InternalServerError();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Context.Dispose();
}
base.Dispose(disposing);
}
}
Issue I am having is that no file is sent to the controller... I can actually see that the image is uploaded on the page though as this is the first step of the download, its sort of a preview of the image before user clicks on the Upload button. The interesting part is that if I make the call from a different html document, one with the structure below, the AJAX Post call does succeed and the file is uploaded successfully !!
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link href="../../site/lib/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<script src="../../Scripts/angular.js"></script>
<script src="../../site/lib/jquery/jquery.min.js"></script>
<script src="../../site/lib/bootstrap/js/bootstrap.min.js"></script>
<script src="../App2/file-upload.js"></script>
</head>
<body ng-app="fupApp" ng-controller="fupController">
<div class="container">
<div class="panel panel-info">
<div class="panel-heading">
Photos
</div>
<div class="panel-body">
<table class="table table-hover table-bordered">
<thead>
<tr>
<td>title</td>
<td>Image</td>
<td>Size</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="image in imagesrc track by $index">
<td>{{image.Name}}</td>
<td>
<img ng-src="{{image.Src}}" title="{{image.Title}}" style="width: 100px;"/>
</td>
<td>{{image.Size}}</td>
</tr>
</tbody>
</table>
<div class="row">
<div class="col-lg-7">
<input type="file" multipe ng-files="getTheFiles($files)" />
</div>
<div class="col-lg-5">
<input ng-disabled="!imagesrc.length" type="button" class="btn btn-success" ng-click="uploadFiles()" value="Upload" />
<input ng-disabled="!imagesrc.length" type="button" class="btn btn-success" ng-click="reset()" value="Cancel" />
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Have tried to change the way the data is sent like below with no joy...
data: formdata
data: [gallery: $scope.galleries[$scope.index].Id]
data: file
Another possible reason could be the scripts I use as they are different on both templates...
Any suggestions ?? many thanks
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="angular/lib/angular.min.js"></script>
<script type="text/javascript" src="js/controller/studentinfo.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="container">
<div id="header">
<h1>
<span class="black-text">School Management Site</span>
</h1>
</div><!--header end-->
<div id="topmenu">
<ul>
<li>
HOME
</li>
<li>
STUDENTS
</li>
<li>
CLASS INFORMARION
</li>
<li>
LOGOUT
</li>
</ul>
</div><!--topmenu end-->
<div id="content">
<div class="jumbotron">
<div ng-controller="studentInfoController" ng-init="getStudentsInfo()">
<form name="studentform" ng-submit="submitStudentForm(studentform.$valid)" novalidate>
<div class="form-group">
<h3>Student Form:</h3>
<h4 style="color: red;">{{errorModel.errorMessage}}</h4>
<label for="rollno" style="color: blue;">StudentRollNo:</label>
<div class="col-sm-12">
<div class="col-sm-3">
<input type="text" class="form-control" id="rollno"
name="studentRollNo" ng-model="student.studentRollNo" required
placeholder="RollNo">
</div>
<div class="col-sm-9">
<span style="color: red"
ng-show="studentform.studentRollNo.$error.required && submitted">
StudentRollNo is required.</span>
</div>
</div>
</div>
<div class="form-group">
<label for="name" style="color: blue;">StudentName:</label>
<div class="col-sm-12">
<div class="col-sm-3">
<input type="text" class="form-control" id="studentName"
name="studentName" ng-model="student.studentName" required
placeholder="StudentName">
</div>
<div class="col-sm-9">
<span style="color: red"
ng-show="studentform.studentName.$error.required && submitted">
StudentName is required.</span>
</div>
</div>
</div>
<div class="form-group">
<label for="name" style="color: blue;">Address:</label>
<div class="form-group">
<div class="col-sm-12">
<div class="col-sm-3">
<input type="text" class="form-control" id="village"
name="village" ng-model="student.village"
placeholder="Village" >
</div>
</div>
</div>
<br/>
<br/>
<div class="col-sm-12">
<div class="col-sm-3">
<input type="text" class="form-control" id="districtName"
name="districtName" ng-model="student.districtName"
placeholder="DistrictName" >
</div>
<div class="col-sm-9">
<span style="color: red"
ng-show="studentform.districtName.$error.required && submitted">
DistrictName is required. </span>
</div>
</div>
</div>
<br/>
<br/>
<div class="form-group">
<div class="col-sm-12">
<div class="col-sm-3">
<input type="text" class="form-control" id="state"
name="state" ng-model="student.state" required
placeholder="State">
</div>
<div class="col-sm-9">
<span style="color: red"
ng-show="studentform.state.$error.required && submitted">
StateName is required.</span>
</div>
</div>
</div>
<br/>
<br/>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
Total Number of Student:<label style="color: black">{{studentsData.length}}</label>
<table id="stuId" border="1" style="color: blue;">
<tr>
<th>StudentRollNo</th>
<th>StudentName</th>
<th>DELETE</th>
<td></td>
</tr>
<tr ng-repeat="student in studentsData" style="color: black;">
<td>
{{student.studentRollNo}}
</td>
<td>
{{student.studentName}}
</td>
<td>
<input type="button" name="info" value="DeleteStudent" ng-click = "deleteStudent({{student.addresId}})">
</td>
</tr>
</table>
</div>
</div>
</div><!--content endss-->
</div><!--container end-->
</body>
when we are loading this page we are getting error
my error is
Error: [$parse:syntax] http://errors.angularjs.org/1.3.15/$parse/syntax?p0=%7B&p1=invalid%20key&p2=16&p3=deleteStudent(%7B%7Bstudent.addresId%7D%7D)&p4=%7Bstudent.addresId%7D%7D)
at ib.equality (http://localhost:8080/SchoolSystem/angular/lib/angular.min.js:196:291)
how can reslove this error
Problem Definition
I am using AngularJS's ngRoute module for the first time and I am running into some trouble with it. I have a index.cshtml page in which I reference my routingModule by setting the ng-app. I also have a ng-view so that when I click on "New Account" it loads register.cshtml in the ng-view or if I click on "Sign In" it will load authenticate.cshtml in the ng-view.
The routing is working as expected since I can see the register and authenticate pages load in the ng-view when I click the links in on my index page. But the controllers I have set for the register and authenticate pages in the routingModule.js seem to not be there.
I get this error when clicking on "New Account" on the index page.
I get the same error when I click on "Sign In" on the index page
I have added all the javascript and html files below needed to solve the problem. Any help would be much appreciated.
Webroot Structure
routingModule.js
var routingModule = angular.module("routingModule", ['ngRoute'])
.config(function ($routeProvider) {
$routeProvider.when('/account/register', { templateUrl: '/account/register/', controller: 'RegisterController' });
$routeProvider.when('/account/authenticate', { templateUrl: '/account/authenticate/', controller: 'AuthenticateController' });
})
index.cshtml
<!DOCTYPE html>
<html ng-app="routingModule">
<head>
<base href="/" />
<script src="~/Scripts/JQuery/jquery-2.1.3.js"></script>
<script src="~/Scripts/Angular/angular.min.js"></script>
<script src="~/Scripts/Angular/angular-route.min.js"></script>
<script src="~/Scripts/Angular/angular-resource.min.js"></script>
<link href="/Content/bootstrap.min.css" rel="stylesheet" />
<link href="/Content/boostrap-hero.min.css" rel="stylesheet" />
<script src="~/Scripts/Bootstrap/bootstrap.min.js"></script>
<script src="/Scripts/app/Registration/registerModule.js"></script>
<script src="/Scripts/App/Registration/registerService.js"></script>
<script src="/Scripts/App/Registration/registerController.js"></script>
<script src="/Scripts/App/Registration/validatePasswordDirective.js"></script>
<script src="~/Scripts/App/Authentication/authenticateModule.js"></script>
<script src="~/Scripts/App/Authentication/authenticateController.js"></script>
<script src="~/Scripts/App/Authentication/authenticateService.js"></script>
<script src="~/Scripts/App/Routing/routingModule.js"></script>
<meta name="viewport" content="width=device-width" />
<title>AngularJS + ASP.NET MVC</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="navbar navbar-default">
<div class="navbar-header">
<ul class="nav navbar-nav">
<li><span class="navbar-brand">AngularJS + ASP.NET Playground</span></li>
</ul>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li> Home</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li> Sign In</li>
<li> New Account</li>
</ul>
</div>
</div>
</div>
<div ng-view></div>
</div>
</body>
</html>
register.cshtml
<form name="registerForm" novalidate>
<div class="row">
<div class="col-md-10">
<h2>Create Account</h2>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Username</label>
<input type="text" name="userName" ng-model="user.userName" class="form-control" required />
<div class="text-danger" ng-show="registerForm.userName.$error.required && registerForm.userName.$dirty">Please enter your first name</div>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" name="email" ng-model="user.email" class="form-control" required ng-pattern="/^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/" />
<div class="text-danger" ng-show="registerForm.email.$error.required && registerForm.email.$dirty">Please enter a your email address</div>
<div class="text-danger" ng-show="registerForm.email.$error.pattern && registerForm.email.$dirty">Invalid email address</div>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" ng-model="user.password" class="form-control" required />
<div class="text-danger" ng-show="registerForm.password.$error.required && registerForm.password.$dirty">Please enter a password</div>
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" name="passwordConfirm" ng-model="user.passwordConfirm" class="form-control" required compare-to="user.password" />
<div class="text-danger" ng-show="registerForm.passwordConfirm.$error.required && registerForm.passwordConfirm.$dirty">Please repeat your password</div>
</div>
<div class="form-group">
<button class="btn btn-default" ng-disabled="registerForm.$invalid" ng-click="register(user)">Create Account</button>
<div style="color: red;" ng-show="errors.length > 0" ng-repeat="error in errors">{{error}}</div>
</div>
</div>
</div>
</form>
authenticate.cshtml
<form name="loginForm" novalidate>
<div class="row">
<div class="col-md-10">
<h2>Sign In</h2>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Email</label>
<input type="text" name="email" ng-model="user.email" class="form-control" required ng-pattern="/^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/" />
<div class="text-danger" ng-show="loginForm.email.$error.required && loginForm.email.$dirty">Please enter a your email address</div>
<div class="text-danger" ng-show="loginForm.email.$error.pattern && loginForm.email.$dirty">Invalid email address</div>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" ng-model="user.password" class="form-control" required />
<div class="text-danger" ng-show="loginForm.password.$error.required && loginForm.password.$dirty">Please enter a password</div>
</div>
<div class="form-group">
<button class="btn btn-default" ng-disabled="loginForm.$invalid" ng-click="authenticate(user)">Sign In</button>
<div style="color: red;" ng-show="errors.length > 0" ng-repeat="error in errors">{{error}}</div>
</div>
</div>
</div>
</form>
registerModule.js
var registerModule = angular.module("registerModule", ["ngResource"]);
registerController.js
registerModule.controller("RegisterController", function ($scope, $location, registerService) {
$scope.register = function (user) {
$scope.errors = [];
registerService.register(user).$promise.then(
function () { $location.url('/home/index');},
function (response){$scope.errors = response.data});
};
});
registerService.js
registerModule.factory('registerService', function ($resource) {
return {
register: function(user) {
return $resource('/api/account/register/').save(user);
}
}
});
From what i can see here, the authenticationModule and registerModule are missing as dependencies of your routingModule:
var routingModule = angular.module("routingModule", ['ngRoute', 'authenticationModule', 'registerModule'])