How to create ng-model array with ng-repeat(number) - angularjs

I have 2 step form
on step 1 : ask user to how many input form needed
that use in < input type="number" ng-model="vm.nkeys" />`
on step 2 : want to create one input text for each with ng-model and name attribute in array form so that I can capture the every input box value; but both is not working; see the relevant code and wokrking plunker below.
<div ng-show="vm.step == 2" ng-form="vm.step2form" class="step-content body" >
<div class="text-center m-t-md">
<div ng-repeat="n in [].constructor(vm.nkeys) track by $index" class="form-group">
<label class="col-sm-2 control-label">{{$index+1}}</label>
<input ng-model="key_desc" name="description_{{n}}" type="text" class="form-control" >
</div>
</div>
</div>
tried ng-model="key_desc[{{$index+1}}] but no success; also name=description_{{$index}} is also not working
see the demo plunker
what do I need to do?

Have a look at the sample snippet below:
<div ng-repeat="item in getNumber(key) track by $index">
<input type="text" ng-model="text[$index]" name="input_{{$index}}" />
<span ng-if="text[$index]">
- {{text[$index]}}
</span>
</div>
Refer the demo here.
See your code now:
<div ng-repeat="n in vm.getNumber(vm.nkeys) track by $index" class="form-group">
<!-- Other stuff -->
<input id="location" ng-model="key_desc[$index]" name="description_{{n}}" type="text" class="form-control" >
</div>
See you code here.

Try this
<input ng-model="key_desc['{{$index}}']" name="description_{{n}}" type="text" class="form-control" >

Set vm variable to ng-model.
(function () {
'user strict';
angular.module('app',[])
.controller('FormController', function ($log) {
var vm = this;
vm.title = 'Key Manager';
vm.step = 1;
vm.key_desc = [];
vm.submit = _submit;
function _submit(){
alert(vm.key_desc);
}
vm.next = function() {
$log.debug('clicked on next');
if(vm.step < 3 )
vm.step = vm.step + 1;
vm.getKeys=function(n){
return new Array(n);
};
}
vm.prev = function() {
$log.debug('clicked on prev');
if(vm.step > 0)
vm.step = vm.step - 1;
}
vm.hasPreviousStep = function(){
var previousStep = vm.step - 1;
return (previousStep > 0);
};
});
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
<link data-require="bootstrap-css#3.2.0" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<link data-require="bootstrap#3.3.2" data-semver="3.3.2" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<script data-require="angular.js#1.5.7" data-semver="1.5.7" src="https://code.angularjs.org/1.5.7/angular.js"></script>
<!--<link rel="stylesheet" href="style.css" />-->
<script src="script.js"></script>
</head>
<body ng-controller="FormController as vm">
<h1>{{vm.title}}</h1>
<div class="row">
<div class="col-lg-7">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>Genarate Key(s)</h5>
</div>
<div class="ibox-content">
<form action="#" class="form" novalidate>
<div role="application" class="wizard clearfix">
<div class="content clearfix">
<div ng-form='vm.step1form' ng-show="vm.step == 1" class="step-content body" >
<div class="m-t-md">
<h2>Number of Keys</h2>
<div class="form-group">
<label class="col-sm-2 control-label">Number of Keys *</label>
<div class="col-sm-4">
<input type="number" min="0" max="50" id="nkeys" name="nkeys" ng-model="vm.nkeys" required class="form-control required" placeholder="How many keys required" />
</div>
</div>
</div>
</div>
<div ng-form="vm.step2form" ng-show="vm.step == 2" class="step-content body" >
<div class="text-center m-t-md">
<h2>This is step 2</h2>
<div ng-repeat="n in [].constructor(vm.nkeys) track by $index" class="form-group">
<label class="col-sm-2 control-label">{{$index+1}}</label>
<div class="col-sm-4">
<input id="location" ng-model="vm.key_desc[$index]" name="description_{{n.name}}" type="text" class="form-control" >
</div>
</div>
</div>
</div>
</div>
<div class="actions clearfix">
<ul class="list-inline">
<li >
<button ng-disabled="vm.step=='1'" type="button" class="btn btn-w-m btn-primary" ng-click="vm.prev()">Previous</button>
</li>
<li >
<button type="button" class="btn btn-w-m btn-primary" ng-click="vm.next()" ng-disabled="!vm.step1form.$valid">Next</button>
</li>
<li >
<button class="btn btn-primary " ng-click="vm.submit()" type="button"><i class="fa fa-check"></i> Submit</button>
</li>
<li>
<button ui-sref="keyhouse.list" type="button" class="btn btn-w-m btn-warning" >Cancel</button>
</li>
</ul>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
model name could be connect with controller name..using vm variable..
In your controller initialize vm.key_desc = [] in your controller..

Use an Array element as ng-model
<input ng-model="key_desc[$index]" name="description_{{n}}"
type="text" class="form-control" >
here the value of first input will be in $scope.key_desc[0], second in $scope.key_desc[1] and so on
before that, initialise $scope.key_desc = [] in your controller

Related

ng-model is not updating the right user in AngularJS

I am kind of new in AngularJS, and I have a form that users can edit there form. But when user clicks update, it updates the form. BUT, the user does not update the user. Shown in the image
Image here
Here is my code:
<div ng-controller="MyCtrl">
<div class="people-view">
<h2 class="name">{{people.first}}</h2>
<h2 class="name">{{people.last}}</h2>
<span class="title">{{people.title}}</span>
<span class="date">{{people.date}} </span>
</div>
</div>
</div>
<!-- the form -->
<div class="list-view">
<form>
<fieldset ng-disabled="inactive">
<legend>Basic Info</legend>
<b>First Name:</b>
<input type="text" ng-model="myObject.first">
<br>
<b>Last Name:</b>
<input type="text" ng-model="myObject.last">
<button type="button" class="edit" ng-show="inactive" ng-click="inactive = !inactive">
Edit
</button>
<button type="submit" class="submit" ng-show="!inactive" ng-click="update()">Update</button>
</form>
App.js
var app = angular.module("Portal", ['ngRoute']);
app.controller('MyCtrl', function($scope) {
$scope.inactive = true;
$scope.people = {};
$scope.myObject = JSON.parse(localStorage.getItem('myObject')) || {
first : $scope.people.first,
last : $scope.people.last,
};
$scope.update = function(){
$scope.people.first = $scope.myObject.first;
$scope.people.last = $scope.myObject.last;
localStorage.setItem('myObject', JSON.stringify($scope.myObject));
};
$scope.deletePeople = deletePeople;
function deletePeople(id){
var userToDelete;
$scope.people.forEach(function(p, index){
if(p.id == id){
userToDelete = index;
}
});
$scope.people.splice(userToDelete, 1);
console.log($scope.people);
}
});
List of users
<div class="people" ng-repeat="p in people | filter:userSearch" >
<a href="#/people/{{ p.id }}">
<img ng-src="{{p.img}}"/>
<span class="name">{{p.first}} </span>
<span class="name">{{p.last}} </span>
<p class="title">{{p.title}} </p>
<span class="date">{{p.date}} </span>
</a>
</div>
The people view section should be included under <div ng-controller="MyCtrl"> div. So just move that line up so it's the first line of the code.
Your ng-model in the form needs to be people.first and people.last respectively. E.g. <b>First Name:</b>
<input type="text" ng-model="people.first">
<br>
<b>Last Name:</b>
<input type="text" ng-model="people.last">
check this
As Swailem95 said you have to move the <div ng-controller="MyCtrl"> top and it looks like below after that.
<div ng-controller="MyCtrl">
<div class="people-view">
<h2 class="name">{{people.first}}</h2>
<h2 class="name">{{people.last}}</h2>
<span class="title">{{people.title}}</span>
<span class="date">{{people.date}} </span>
</div>
<!-- the form -->
<div class="list-view">
<form>
<fieldset ng-disabled="inactive">
<legend>Basic Info</legend>
<b>First Name:</b>
<input type="text" ng-model="myObject.first">
<br>
<b>Last Name:</b>
<input type="text" ng-model="myObject.last">
</fieldset>
<button type="button" class="edit" ng-show="inactive" ng-click="inactive = !inactive">
Edit
</button>
<button type="submit" class="submit" ng-show="!inactive" ng-click="update()">Update</button>
</form>
</div>
</div>

Controller Value is not showing in view Angularjs

In the view {{phonenumber}} value is not updating. But When I enter digits alert is working properly inside the controller.
Controller
var app = angular.module('myApp', []);
app.controller('PosController', function ($scope, $http) {
$scope.phonenumberFromDial = "";
$scope.phonenumber = "";
$scope.updatePhoneNumber = function(id) {
$scope.phonenumberFromDial=id;
$scope.phonenumber =$scope.phonenumber+$scope.phonenumberFromDial;
if($scope.phonenumber.length > 9) {
console.log("Log phonenumber: " + $scope.phonenumberFromDial);
alert('Here the Number: '+ $scope.phonenumber);
}
});
View
<div ng-app="myApp" ng-controller="PosController" class="panel" >
<div class="input-group col-xs-4">
<div class="input-group-btn">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal">Telefono</button>
</div><!-- /btn-group -->
<div ng-app="myApp" ng-controller="PosController">
<input id="phonenumber" class="form-control" ng-model="phonenumber" />
<!--<input type="text" id="phonenumber" ng-model="myModel" ng-keyup="(myModel.length >= 3) && myFunction()" class="form-control" data-inputmask='"mask": "(999) 999-9999"' data-mask>-->
</div>
<div class="input-group-btn" >
<button type="button" class="btn btn-success">Cliente</button>
</div><!-- /btn-group -->
<div ng-app="myApp" ng-controller="PosController">\
<input type="text" id="cliente" class="form-control" value="{{phonenumber}}">
</div>
</div>
</div>
Some observations :
remove unecessary multiple ng-controller="PosController" and ng-app="myApp" from the code and leave with only one at the top.
use ng-model="phonenumber" instead of value="{{phonenumber}}" to perform two way data binding.
Working demo :
var app = angular.module('myApp', []);
app.controller('PosController', function ($scope, $http) {
$scope.phonenumberFromDial = "";
$scope.phonenumber = "";
$scope.updatePhoneNumber = function(id) {
$scope.phonenumberFromDial=id;
$scope.phonenumber =$scope.phonenumber+$scope.phonenumberFromDial;
if($scope.phonenumber.length > 9) {
console.log("Log phonenumber: " + $scope.phonenumberFromDial);
alert('Here the Number: '+ $scope.phonenumber);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="PosController" class="panel" >
<div class="input-group col-xs-4">
<input type="text" id="phonenumber" class="form-control" ng-model="phonenumber"/>
<div class="input-group-btn" >
<button type="button" class="btn btn-success" ng-click="updatePhoneNumber(phonenumber)">Cliente</button>
</div>
<input type="text" id="cliente" class="form-control" ng-model="phonenumber">
</div>
</div>
There are several things you're missing. First of the all, as suggested in comment, you only need to declare ng-app and ng-controller once in the HTML with np-app on the top-most level. Secondly, you bind the scope data to the HTML using ng-model inside a input field, or {{phonenumber}} in HTML. Third, you forgot to close the controller with an ending parenthesis.
Here is a working demo:
var app = angular.module('myApp', []);
app.controller('PosController', function ($scope, $http) {
$scope.phonenumberFromDial = "";
$scope.phonenumber = "";
$scope.updatePhoneNumber = function(id) {
$scope.phonenumberFromDial=id;
$scope.phonenumber =$scope.phonenumber+$scope.phonenumberFromDial;
if($scope.phonenumber.length > 9) {
console.log("Log phonenumber: " + $scope.phonenumberFromDial);
alert('Here the Number: '+ $scope.phonenumber);
}
}
});
<!doctype html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="app.js"></script>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.0.4/css/bootstrap-combined.min.css">
</head>
<body>
<div class="panel" >
<div class="input-group col-xs-4" ng-controller="PosController">
<div class="input-group-btn">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal">Telefono</button>
</div><!-- /btn-group -->
<div>
<input id="phonenumber" class="form-control" ng-model="phonenumber" />
<!--<input type="text" id="phonenumber" ng-model="myModel" ng-keyup="(myModel.length >= 3) && myFunction()" class="form-control" data-inputmask='"mask": "(999) 999-9999"' data-mask>-->
</div>
<div class="input-group-btn" >
<button type="button" class="btn btn-success">Cliente</button>
</div><!-- /btn-group -->
<div>
<input type="text" id="cliente" class="form-control" ng-model="phonenumber">
</div>
<span>Phone#: {{phonenumber}}</span>
<div>
Dial: <input type="text" id="cliente" class="form-control" ng-model="phonenumberFromDial">
</div>
<div class="input-group-btn" >
<button type="button" class="btn btn-success" ng-click="updatePhoneNumber(phonenumberFromDial)">Update phone#</button>
</div><!-- /btn-group -->
</div>
</div>
</body>
</html>

AngularJS Validations for multiple fields

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>

uploadFiles angularjs function, data not found during AJAX call

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

Load html controls based on JSON in angular js

I have a form to generate JSON format in bottom we can see. I will select name and control that need to display.How ever from the JSON data which I get from this form. I need to display all the controls in another form or same form. if I select Textbox it should display textbox.
if any one knows to display or render the controls from JSON that will great helpfull.
Here is the code:
var app = angular.module('Example',[]);
app.controller("ExampleController",function ($scope){
$scope.Controls=[];
$scope.master= {};
$scope.update = function(user) {
// Example with 1 argument
debugger;
$scope.Controls.push(angular.copy(user));
$scope.master= $scope.Controls;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<body ng-app="Example">
<table class="table table-striped">
<tr>
<td style="width:60%">
<div class="panel panel-default" style="">
<div class="panel-heading">Screen Builder</div>
<div class="panel-body">
<div class="panel panel-default form-left" >
<div class="panel-body" ng-controller="ExampleController">
<div class="row">
<div class="col-md-offset-1 col-md-10" >
<form class="form-horizontal " ng-submit="update(user)">
<div class="form-group">
<div class="row">
<div class="col-md-4">
<label >Form Name :</label>
</div>
<div class="col-md-8">
<input type="text" ng-model="user.Form">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-4">
<label >Control :</label>
</div>
<div class="col-md-8 text-justify">
<div class="row">
<div class="col-md-6">
<input type="radio" name="Label" value="Label" ng-model="user.Control.type">Label
</div>
<div class="col-md-6">
<input type="radio" name="Label" value="Combo" ng-model="user.Control.type">Combo
</div>
<div class="col-md-6">
<input type="radio" name="Label" value="Edit Combo" ng-model="user.Control.type">Edit Combo
</div>
<div class="col-md-6">
<input type="radio" name="Label" value="Combo Grid" ng-model="user.Control.type">Combo Grid
</div>
<div class="col-md-6">
<input type="radio" name="Label" value="Date" ng-model="user.Control.type">Date
</div>
<div class="col-md-6">
<input type="radio" name="Label" value="Date Time" ng-model="user.Control.type">Date Time
</div>
<div class="col-md-6">
<input type="radio" name="Label" value="Number" ng-model="user.Control.type">Number
</div>
<div class="col-md-6">
<input type="radio" name="Label" value="Check Box" ng-model="user.Control.type">Check Box
</div>
<div class="col-md-6">
<input type="radio" name="Label" value="Option Button" ng-model="user.Control.type">Option Button
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-4">
<label >Caption :</label>
</div>
<div class="col-md-8">
<input type="text" ng-model="user.Control.value">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 text-center">
<input type="submit" style="width: 60px" value="Submit">
</div>
</div>
</form>
<pre>master = {{master | json}}</pre>
</div>
</div>
</div>
</div>
</div>
</div>
</td>
<td style="width: 60%"></td>
</tr>
</table>
</body>
Here's one way of doing it - Plunker.
It's a simple example that doesn't add all the elements in the main form but it is to show you how it could be done. The idea is to have a dummy form that you append elements to.
JS
app.controller("ExampleController",function ($scope, $element){
$scope.Controls=[];
$scope.master= {};
var newForm = angular.element($element[0].querySelector('#newForm'));
$scope.update = function(user) {
// Example with 1 argument
$scope.Controls.push(angular.copy(user));
$scope.master= $scope.Controls;
if (user !== undefined) {
var element = "";
if (user.Control.type == "Label") {
if (user.Control.hasOwnProperty("value")) {
element = "<div class='col-md-6'><label>" + user.Control.value + "</label></div>";
}
else {
element = "<div class='col-md-6'><label>Label</label></div>";
}
}
else if (user.Control.type == "Check Box") {
if (user.Control.hasOwnProperty("value")) {
element = "<div class='col-md-6'><input type='checkbox'>" + user.Control.value + "</input></div>";
}
else {
element = "<div class='col-md-6'><input type='checkbox'></input></div>";
}
}
newForm.append(element)
}
};
});
Markup
<!-- New form -->
<br>
<div>
New Form:
<form id="newForm" class="form-horizontal ">
</form>
</div>
Let me know if you want to add the elements by traversing the JSON instead.

Resources