I have ASP.NET MVC application and I am trying simple example where submit form is handle by ng-submit and alert value of input using angularJS. my first part of angularJS (display record in table ng-repeat) is working but not form, not sure what I am missing here!
https://jsfiddle.net/toxic_kz/srs69ppp/2/
HTML
<div>{{ "Two plus Two equals: " + (2+2) }}</div>
<div ng-controller="tripsControllers as vm" class="col-md-6 col-md-offset-3" style="width:100%">
<table class="table table-responsive table-striped">
<tr ng-repeat="trip in vm.trips">
<td>{{ trip.name }}</td>
<td>{{ trip.created | date: 'dd-MM-yyyy'}}</td>
<td>Manage</td>
</tr>
</table>
<form novalidate name="NewTripForm" ng-submit="vm.addTrip()">
<div class="form-group">
<label for="name">New Trip Name</label>
<input class="form-control" type="text" id="name" name="name" ng-model="vm.newTrip.name" />
</div>
<div class="form-group">
<label>Testing Button</label>
<input class="btn btn-success" type="button" value="testing" id="testA" ng-click="alert('testing A Button')" />
</div>
<div class="form-group">
<input class="btn btn-success btn-sm" type="submit" value="Add" />
</div>
</form>
</div>
AngularJS
(function () {
"use strict";
angular.module("app-trips", []);
})();
(function () {
"use strict";
angular.module("app-trips")
.controller("tripsControllers", tripsController);
function tripsController()
{
var vm = this;
vm.trips = [{
name: "US trip",
created: new Date()
},
{
name: "World trip",
created: new Date()
}
];
vm.newTrip = {};
vm.addTrip() = function () {
alert(vm.newTrip.name);
};
}
})();
I have added your code in a plunker to make it work.
app.js:
var app = angular.module('plunker', []);
app.controller('tripsControllers', function($scope) {
var vm = this;
vm.trips = [{
name: "US trip",
created: new Date()
},
{
name: "World trip",
created: new Date()
}
];
vm.newTrip = {};
vm.addTrip = function () {
alert(vm.newTrip.name);
};
});
index.html
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.10/angular.min.js" data-semver="1.5.10"></script>
<script src="app.js"></script>
</head>
<body>
<div>{{ "Two plus Two equals: " + (2+2) }}</div>
<div ng-controller="tripsControllers as vm" class="col-md-6 col-md-offset-3" style="width:100%">
<table class="table table-responsive table-striped">
<tr ng-repeat="trip in vm.trips">
<td>{{ trip.name }}</td>
<td>{{ trip.created | date: 'dd-MM-yyyy'}}</td>
<td>Manage</td>
</tr>
</table>
<form novalidate name="NewTripForm" ng-submit="vm.addTrip()">
<div class="form-group">
<label for="name">New Trip Name</label>
<input class="form-control" type="text" id="name" name="name" ng-model="vm.newTrip.name" />
</div>
<div class="form-group">
<label>Testing Button</label>
<input class="btn btn-success" type="button" value="testing" id="testA" ng-click="alert('testing A Button')" />
</div>
<div class="form-group">
<input class="btn btn-success btn-sm" type="submit" value="Add" />
</div>
</form>
</div>
</body>
</html>
https://plnkr.co/edit/7X73A8GidqIzF91fmlkK
Related
I am developing an app using angularjs. I need to add date time picker to my form. but not sure how to add it.
you can use this
angularjs-datetime-picker
:)
var app = angular.module('myApp', ['angularjs-datetime-picker']);
app.run(function($rootScope) {
$rootScope.gmtDate = new Date('2015-01-01 00:00:00 -00:00');
});
app.controller("ctrl", function($scope) {
$scope.model = "1/1/1991";
$scope.rows = ['Paul', 'John', 'Lucie'];
$scope.temp = false;
$scope.addRow = function() {
$scope.temp = false;
$scope.addName = "";
};
$scope.deleteRow = function(row) {
$scope.rows.splice($scope.rows.indexOf(row), 1);
};
$scope.plural = function(tab) {
return tab.length > 1 ? 's' : '';
};
$scope.addTemp = function() {
if ($scope.temp) $scope.rows.pop();
else if ($scope.addName) $scope.temp = true;
if ($scope.addName) $scope.rows.push($scope.addName);
else $scope.temp = false;
};
$scope.isTemp = function(i) {
return i == $scope.rows.length - 1 && $scope.temp;
};
});
body {
padding: 20px;
}
.search {
margin-left: 10px;
}
<!DOCTYPE html>
<html ng-app="myApp" ng-init="
date1='01-01-2015 00:00:00';
date2='Thu Jan 01 2015 00:00:00 GMT-0500 (EST)';
date3='2015-01-01T00:00:00-0400';
date4='2015-01-01';">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/angularjs-datetime-picker-v2#0.2.2/angularjs-datetime-picker.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/angularjs-datetime-picker-v2#0.2.2/angularjs-datetime-picker.css">
<!-- -->
<!-- <link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script> -->
<meta charset=utf-8 />
<title>Angular JS Demo</title>
</head>
<body ng-controller="ctrl">
<input ng-model="date4" datetime-picker date-only /> <br>
<input ng-model="date1" datetime-picker="" date-only="" size="30" class="ng-pristine ng-valid ng-valid-date ng-touched"> <br> <br> <input ng-model="date2" datetime-picker date-format="yyyy-MM-dd" date-only /> <br>
<input ng-model="date2" datetime-picker="" date-format="yyyy-MM-dd" size="30" date-only="" class="ng-pristine ng-valid ng-valid-date ng-touched"> <br> <br> <br> <input ng-model="date3" datetime-picker date-format="yyyy-MM-dd HH:mm:ss" close-on-select="false"
/> <br>
<input ng-model="date3" datetime-picker="" date-format="yyyy-MM-dd HH:mm:ss" close-on-select="false" size="30" class="ng-pristine ng-valid ng-valid-date ng-touched"> <br> <br> <input ng-model="date4" datetime-picker hour="23" minute='59'/><br>
<input ng-model="date4" datetime-picker="" hour="23" minute="59" size="30" class="ng-pristine ng-valid ng-valid-date ng-touched"> <br> <br> gmtDate : "2020-01-01T11:58:00.000Z"<br> <input type="date" ng-model="gmtDate" size="30" /><br>
<input datetime-picker ng-model="addName" />
<h2>{{rows.length}} Friend{{plural(rows)}} <span ng-show="temp">?<small class="muted"><em > (only {{rows.length-1}} actually....)</em></small></span></h2>
<form class="form-horizontal">
<span ng-class="{'input-append':addName}">
<input id="add" type="text" placeholder="Another one ?" ng-model="addName" ng-change="addTemp()"/>
<input type="submit" class="btn btn-primary" ng-click="addRow()" ng-show="addName" value="+ add"/>
</span>
<span class="search input-prepend" ng-class="{'input-append':search}">
<span class="add-on"><i class="icon-search"></i></span>
<input type="text" class="span2" placeholder="Search" ng-model="search">
<button type="submit" class="btn btn-inverse" ng-click="search=''" ng-show="search" value="+ add"><i class="icon-remove icon-white"></i></button>
</span>
</form>
<table class="table table-striped">
<tr ng-repeat="row in rows | filter : search" ng-class="{'muted':isTemp($index)}">
<td>{{$index+1}}</td>
<td>{{row}}</td>
<td>
<button class="btn btn-danger btn-mini" ng-click="deleteRow(row)" ng-hide="isTemp($index)"><i class="icon-trash icon-white"></i></button>
</td>
</tr>
</table>
</body>
</html>
HTML code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<br /><br />
<div class="container" style="width:500px;">
<h3 align="center">Registration Form</h3>
<div ng-app="myapp" ng-controller="usercontroller">
<input type="hidden" ng-value="id" name="id" ng-model="id" class="form-control" />
<label>First Name</label>
<input type="text" ng-value="name" name="first_name" ng-model="firstname" class="form-control" />
<br />
<label>Last Name</label>
<input type="text" ng-value="lname" name="last_name" ng-model="lastname" class="form-control" />
<br />
<input type="submit" name="btnInsert" class="btn btn-info" ng-click="insertData()" value="ADD"/>
<hr>
<p style="text-align: center;">User List</p>
<hr>
<table class="table table-striped">
<tr >
<td>S.no</td>
<td>First Name</td>
<td>Last Name</td>
<td style="text-align: center;" ng-click=>Action</td>
</tr>
<tr ng-repeat="x in names">
<td>{{$index +1}}</td>
<td>{{x.first_name}}</td>
<td>{{x.last_name}}</td>
<td>Delete</td>
<td>Edit</td>
</tr>
</table>
</div>
</div>
</body>
</html>
Script Code:
<script>
var app = angular.module("myapp",[]);
app.controller("usercontroller", function($scope, $http){
$scope.id=0;
$scope.Edit=function(id){
$http.post(
"<?php echo BASE_URL;?>Registration/Edit",
{id :id}
).then(function(response){
$scope.name = response.data.first_name;
$scope.lname = response.data.last_name;
$scope.id = response.data.id;
});
}
$scope.Delete=function(id){
$http.post(
"<?php echo BASE_URL;?>Registration/Del",
{id :id}
).then(function(response){
name();
//alert('ok');
});
}
$scope.insertData = function(){
if($scope.id==0){
$http.post(
"<?php echo BASE_URL;?>Registration/add",
{'firstname':$scope.firstname, 'lastname':$scope.lastname}
).then(function(response){
name();
$scope.firstname = null;
$scope.lastname = null;
});
}
else{
//Here i am not getting the change value from the text box it give me the same value or old value from the text field
alert($scope.name);
}
}
var name=function(){
$http.get("<?php echo BASE_URL;?>Registration/view").then(function(response){
$scope.names = response.data;
});
}
name();
});
</script>
This is my front end page for angular crud all listing ,add ,del working fine but the problem is that when i am going to set the value on text field using edit function after how can i get the value after text change its returning me only set value of text after modify this value m not able to get new value please help me related this i am newbe here.
1) You remove ng-value for all the inputs in the HTML
2) in $scope.edit method, append the response data to the models $scope.firstname, $scope.lastname and $scope.id
These two changes should solve your prob. Angular models supports two way binding.
I am working on dynamic forms with ng-repeat. I am using the oi-select library for loading my locations. The oi-select box has multi select feature. on my page loading by default, I am loading first option value in that oi-select box.
But I am using a multi select feature if I select any other option than the first option it gets override with that value. Due to this issue, I have to select again that first option. My question is, how can I load my first option value by default into that oi-select?
Afterwards, if I am select any other options it won't override my first value in select box .Here is my plunker link http://plnkr.co/edit/m6Q02dlHLBCMVLRLfioh?p=preview
my HTML code
<body class="container row">
<div ng-app="myApp">
<div ng-controller="myCtrl">
<form role="form" name='userForm' novalidate>
<div class="container">
<div class="row" ng-repeat="user in users">
<div class="form-group">
<div class="col-md-3">
<label>ID</label>
<input ng-model="user.id" id="user.id" name="user.id" placeholder="Enter bugid" type="text" required readonly disabled>
</div>
<div class="col-md-3">
<label>Comments</label>
<textarea ng-model="user.comment" id="textarea1" rows="1" required></textarea>
</div>
<div class="col-md-3 ">
<label>Location</label>
<oi-select ng-model="user.location" multiple oi-options="v for v in locations" ng-init='initLocation(user)' name="select2" required>
</oi-select>
</div>
</div>
</div>
</div>
<div class="buttonContainer text-center btn-container">
<br>
<button ng-disabled="userForm.$invalid" type="button" id="adduser" ng-click="adduser()">Add user</button>
<button type="button" class="btn button--default btn--small pull-center">Close</button>
</div>
</form>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />
<script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
</div>
</div>
my js code
var app = angular.module('myApp', ['ngResource', 'oi.select']);
app.controller('myCtrl', function($scope, $timeout) {
$scope.ids = [1, 2, 3];
$scope.users = $scope.ids.map(function(id) {
return {
id: id,
comment: "",
location: ""
};
});
$scope.locations = ['india', 'usa', 'jermany', 'china', 'Dubai'];
$scope.initLocation = (user) => {
$timeout(() => {
user.location = $scope.locations[0];
});
}
$scope.adduser = function() {
var data = $scope.users.map(function(user) {
return {
"userid": user.id,
"manualcomment": user.comment,
"location": user.location
}
});
console.log("data", data)
}
});
If you use multiple attribute, this means the model should be an array and not a string as in your case user.location = $scope.locations[0];, ypu have to change it to location: [] and use push() method to add the initial items to this array;
Using $timeout doesn't make any sense to me;
ngInit adds unnecessary amount of logic into the template, I would prefer avoid using it in you case, just use location: [$scope.locations[0]] in your controller.
Working example:
var app = angular.module('myApp', ['ngResource', 'oi.select']);
app.controller('myCtrl', function($scope, $timeout) {
$scope.ids = [1, 2];
$scope.locations = ['india', 'usa', 'jermany', 'china', 'Dubai'];
$scope.users = $scope.ids.map(function(id) {
return {
id: id,
comment: "",
location: []
};
});
$scope.initLocation = (user, locations) => {
if (!user.location.length) {
user.location.push(locations[0]);
}
}
$scope.adduser = function() {
$scope.users.push({
id: Math.max(...($scope.users.map(u => { return u.id; }))) + 1,
comment: "added from controller",
location: [$scope.locations[2]]
});
}
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link data-require="bootstrap#3.3.5" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<link rel="stylesheet" href="//rawgit.com/tamtakoe/oi.select/master/dist/select.css" />
<script>document.write('<base href="' + document.location + '" />');</script>
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"></script>
<script data-require="angular-resource#1.4.3" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular-resource.js"></script>
<script src="//rawgit.com/tamtakoe/oi.select/master/dist/select-tpls.js"></script>
<script src="script.js"></script>
</head>
<body class="container row">
<div ng-app="myApp">
<div ng-controller="myCtrl">
<form role="form" name='userForm' novalidate>
<div class="container">
<div class="row" ng-repeat="user in users">
<div class="form-group">
<div class="col-md-3">
<label>ID</label>
<input ng-model="user.id" id="user.id" name="user.id" placeholder="Enter bugid" type="text" required readonly disabled>
</div>
<div class="col-md-3">
<label>Comments</label>
<textarea ng-model="user.comment" id="textarea1" rows="1" required></textarea>
</div>
<div class="col-md-3 ">
<label>Location</label>
<oi-select ng-model="user.location"
multiple oi-options="v for v in locations" ng-init='initLocation(user, locations)'
name="select2" required>
</oi-select>
</div>
</div>
</div>
</div>
<div class="buttonContainer text-center btn-container">
<br>
<button ng-disabled="userForm.$invalid" type="button" id="adduser" ng-click="adduser()">Add user</button>
<button type="button" class="btn button--default btn--small pull-center">Close</button>
</div>
</form>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />
<script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
</div>
</body>
</html>
I'm creating an Angular app that adds info to a list but I can't seen to get the item to post. I want the use to add info to the form then the info is then add to the responsive table. I'm not sure if the function for the inputs are correct. Check out my code below.
angular.module('LumpSumApp', [])
.controller('LumpSumController', function() {
var lumpSumList = this;
lumpSumList.addLumpSum = function() {
lumpSumList.lumpsums.push({ select: lumpSumList.lumpSumType, done: false });
lumpSumList.lumpSumType = '';
lumpSumList.lumpsums.push({ select: lumpSumList.lumpSumCategory, done: false });
lumpSumList.lumpSumCategory = '';
lumpSumList.lumpsums.push({ text: lumpSumList.lumpSumEstimate, done: false });
lumpSumList.lumpSumEstimate = '';
lumpSumList.lumpsums.push({ text: lumpSumList.lumpSumExpenses, done: false });
lumpSumList.lumpSumExpenses = '';
lumpSumList.lumpsums.push({ file: lumpSumList.lumpSumQuote, done: false });
lumpSumList.lumpSumQuote = '';
lumpSumList.lumpsums.push({ file: lumpSumList.lumpSumReceipt, done: false });
lumpSumList.lumpSumReceipt = '';
};
});
<form class="form-inline" ng-submit="lumpSumList.addLumpSum()">
<div class="form-group">
<select class="form-control" ng-model="lumpSumList.lumpSumType">
<option>Select a Type</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
<div class="form-group">
<select class="form-control" ng-model="lumpSumList.lumpSumCategory">
<option>Select a Category</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
<div class="form-group">
<input class="form-control" type="text" ng-model="lumpSumList.lumpSumEstimate" size="40" placeholder="Estimated Expenses">
</div>
<div class="form-group">
<input class="form-control" type="text" ng-model="lumpSumList.lumpSumExpenses" size="40" placeholder="Actual Expenses">
</div>
<div class="form-group">
<label class="btn btn-primary">
<i class="fa fa-file-text-o" aria-hidden="true"></i>
<input type="file" ng-model="lumpSumList.lumpSumQuote" style="display: none;">
</label>
</div>
<div class="form-group">
<label class="btn btn-primary">
<i class="fa fa-file-text-o" aria-hidden="true"></i>
<input type="file" ng-model="lumpSumList.lumpSumReceipt" style="display: none;">
</label>
</div>
<input class="btn btn-primary" type="submit" value="add">
</form>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Expense Type</th>
<th>Expense Category</th>
<th>Estimated Expenses</th>
<th>Actual Expenses</th>
<th>Upload Quote(s)</th>
<th>Upload Receipt(s)</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="lumpsum in lumpSumList.lumpsums">
<td>{{lumpSumList.lumpSumType}}</td>
<td>{{lumpSumList.lumpSumCategory}}</td>
<td>{{lumpSumList.lumpSumEstimate}}</td>
<td>{{lumpSumList.lumpSumExpenses}}</td>
<td>{{lumpSumList.lumpSumQuote}}</td>
<td>{{lumpSumList.lumpSumReceipt}}</td>
</tr>
</tbody>
</table>
</div>
I reworked your code with changes to handle an array of objects.
The two keys here are the changes to the controller code and the changes to the HTML.
In the JavaScript, we first initialize the lumpSumList.lumpsums when the controller loads. Then, inside the function, each time the addLumpSum button is clicked, we create a new object to hold all the properties from the dropdowns, then push this object into the array.
In the HTML, we output the lumpsum values, rather than the dropdown values. Just as a quick fix, I also added value='' to the default options in the dropdown to get rid of the empty option.
angular.module('LumpSumApp', [])
.controller('LumpSumController', function() {
var lumpSumList = this;
lumpSumList.lumpsums = [];
lumpSumList.addLumpSum = function() {
var lumpsum = {
lumpSumType: lumpSumList.lumpSumType,
lumpSumCategory: lumpSumList.lumpSumCategory,
lumpSumEstimate: lumpSumList.lumpSumEstimate,
lumpSumExpenses: lumpSumList.lumpSumExpenses
};
lumpSumList.lumpsums.push(lumpsum);
lumpSumList.lumpSumType = '';
lumpSumList.lumpSumCategory = '';
lumpSumList.lumpSumEstimate = '';
lumpSumList.lumpSumExpenses = '';
};
});
<!DOCTYPE html>
<html ng-app="LumpSumApp">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<script src="app.js"></script>
</head>
<body ng-controller="LumpSumController as lumpSumList">
<form class="form-inline" ng-submit="lumpSumList.addLumpSum()">
<div class="form-group">
<select class="form-control" ng-model="lumpSumList.lumpSumType">
<option value=''>Select a Type</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
<div class="form-group">
<select class="form-control" ng-model="lumpSumList.lumpSumCategory">
<option value=''>Select a Category</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
<div class="form-group">
<input class="form-control" type="text" ng-model="lumpSumList.lumpSumEstimate" size="40" placeholder="Estimated Expenses">
</div>
<div class="form-group">
<input class="form-control" type="text" ng-model="lumpSumList.lumpSumExpenses" size="40" placeholder="Actual Expenses">
</div>
<div class="form-group">
<label class="btn btn-primary">
<i class="fa fa-file-text-o" aria-hidden="true"></i>
<input type="file" ng-model="lumpSumList.lumpSumQuote" style="display: none;">
</label>
</div>
<div class="form-group">
<label class="btn btn-primary">
<i class="fa fa-file-text-o" aria-hidden="true"></i>
<input type="file" ng-model="lumpSumList.lumpSumReceipt" style="display: none;">
</label>
</div>
<input class="btn btn-primary" type="submit" value="add">
</form>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Expense Type</th>
<th>Expense Category</th>
<th>Estimated Expenses</th>
<th>Actual Expenses</th>
<th>Upload Quote(s)</th>
<th>Upload Receipt(s)</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="lumpsum in lumpSumList.lumpsums">
<td>{{lumpsum.lumpSumType}}</td>
<td>{{lumpsum.lumpSumCategory}}</td>
<td>{{lumpsum.lumpSumEstimate}}</td>
<td>{{lumpsum.lumpSumExpenses}}</td>
<td>{{lumpsum.lumpSumQuote}}</td>
<td>{{lumpsum.lumpSumReceipt}}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
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