AngularJS 1.x: Dynamically created multiple File Upload fields - angularjs

You have to excuse me, I do not use Angular that often. I need to implement a solution in which I can upload files from dynamically generated input fields.
The catch is that I cannot use any directives (this is due to the framework I am using in which AngularJS is implemented).
My current code for creating fields:
$scope.addNewFile = function() {
var newFileNo = $scope.files.length + 1;
$scope.files.push({'id': 'file' + newFileNo});
};
$scope.removeFile = function() {
var lastFile = $scope.files.length - 1;
$scope.files.splice(lastFile);
};
And here is the code for uploading files (not correct, because of static id and name values:
$scope.uploadFile = function() {
var file = document.getElementById('file').files[0],
r = new FileReader;
r.onloadend = function (e) {
var data = e.target.result;
console.log('data');
console.log(data);
// http.post
};
r.readAsArrayBuffer(file);
};
And here is my HTML:
<div data-ng-repeat="file in files">
<div class="row top-buffer">
<div class="col-lg-10">
<input type="file"
ng-model="file.name"
name="file"
class="form-control"
id="file">
</div>
<div class="col-lg-2 text-right">
<div class="btn btn-primary" ng-click="uploadFile()">Upload</div>
</div>
</div>
</div>
<div class="row top-buffer">
<div class="col-lg-11"></div>
<div class="col-lg-1 text-right">
<div class="glyphicon glyphicon-plus" aria-hidden="true" ng-click="addNewFile()"></div>
<div class="glyphicon glyphicon-minus" aria-hidden="true" ng-click="removeFile()"></div>
</div>
</div>
I can't really understand how I can get the values of dynamically generated file fields... any help appreciated!

There is no ng-model for <input type=file, but you can achieve what you want setting the id dynamically with ng-attr:
<div ng-repeat="file in files">
{{file.id}}:
<input type="file"
ng-attr-name="{{file.id}}"
ng-attr-id="{{file.id}}">
</div>
On uploadFile() you can post them:
$scope.uploadFile = function() {
$scope.files.forEach(function(file) {
// $http.post: document.getElementById(file.id).files[0])
});
};
Example on Fiddle: https://jsfiddle.net/virgilioafonsojr/92nw4j4f/1/
I hope it helps.

Writing an uploader properly is a very difficult task. A major problem with an upload component/directive is getting it to work in Internet Explorer; because it can only be used once in IE. Another problem is that IE will not let you programmatically "press" the button, it must be a real mouse click.
There are upload libraries out there for AngularJs, just google. However if you are intent on doing it yourself then you can use my git repo as an example of how it should be done. Just use the jwtUploader and jwtUploaderButton directives.
https://github.com/smylydon/SEPE-7WCM0033-0206-FRONTEND/tree/master/client/app

Related

Angular.js $cookies : not properly saved/loaded

I am trying to use a simple input that can be retrieved by a cookie automatically.
My angular controller is :
<script>
var app = angular.module('mantis', ['ngCookies']);
app.controller('main', function($scope, $cookies) {
$scope.nom = '';
$scope.WriteNom = function () {
$cookies.put('Nom', $scope.nom);
};
$scope.ReadNom = function () {
$scope.nom = $cookies.get('Nom');
return $scope.nom;
};
});
</script>
In my page, I made a div where I can change the variable "nom" flawlessly.
The value should be loaded with ng-init (from cookie)
It changes with ng-model
And it should be saved with ng-click
<div class="container" ng-app="mantis" ng-controller="main">
<!-- Assigné à -->
<div class="col-lg-12">
<div class="input-group" ng-init="nom=ReadNom()">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input id="nom" type="text" class="form-control" name="nom" placeholder="Assigné à (id)" ng-model="nom">
<span class="input-group-btn">
<button class="btn btn-secondary" type="button" ng-click="WriteNom()">Sauvegarder</button>
</span>
</div>
</div>
(...)
And then, somewhere else, i can use "nom" where I need it by using {{nom}}
It's almost working :
The value is properly changed when I type in the input box and I can use it
The cookie is not changed when I click on the button nor it's loaded when I load the page
Remove the return part,
HTML:
<div class="input-group" ng-init="ReadNom()">
Controller:
$scope.ReadNom = function () {
$scope.nom = $cookies.get('Nom');
};
DEMO

How to add text box runtime and insert its value to db in angularjs

I want to create Curd app using AngularJS & MVC.
In that I am able to add, update and delete particular data from grid, but there is one task where I am getting stuck.
Here what I need to do is, I should be able to add multiple run time text box on that insert page to take any no of input from user, so I don't know how to do it and how to add those run time added text box values in DB.
It would be much appreciated if you help me on this.
Try this,
Here is the working fiddle
<div ng-controller="MyCtrl">
<div class="row" ng-repeat="(key,val) in data">
<div class="col-md-12">
<input type="text" ng-model="val.text">
</div>
</div>
<div class="row">
<div class="col-md-12">
<button class="btn btn-primary" ng-click="addTextbox()">
Add Textbox
</button>
</div>
<div class="col-md-12">
<button class="btn btn-success" ng-click="sendDataToServer()">
Send Data
</button>
</div>
</div>
<div class="row">
<div class="col-md-12">
Result = {{data}}
</div>
</div>
</div>
Controller's code
var myApp = angular.module('myApp',[]);
function MyCtrl($scope,$http) {
$scope.data = [];
$scope.addTextbox = function(){
$scope.data.push({'text':''});
}
$scope.sendDataToServer = function(){
console.log(JSON.stringify($scope.data));
$http({
url: 'your_server_url',
method: "POST",
data: JSON.stringify($scope.data),
headers: {
'Content-Type': undefined
}
}).then(function(res) {
// do stuff on success
}, function(errorMsg) {
console.log(errorMsg);
// showing error
});
}
}
Here you will get all textbox's data into $scope.data, Now you can send this data by clicking Send Data button.
Provide the url where you want to submit this data.
Comment if you have any issue.

create data driven angular form

I have a project that needs to create a form with the title of each text field comes from a json from another server.
I need to use ng-repeat to show the title and use ng-model for the text field itself, but how do I return all the result back to the server in a json format?
Here is my html part
<div class="row" ng-controller="createworkshopController">
<form role="form" ng-submit="submitWorkshop()">
<div>
<div ng-repeat="x in form">
<h4>{{x.field_name}}</h4>
<input class="form-control" placeholder="{{x.field_name}}" ng-model="result.form[field_name]">
</div>
</div>
<hr>
<div align="right">
<button type="submit" class="btn btn-default" ng-click="submitWorkshop()">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</div>
</form>
</div>
And here is what I have for angular controller
app.controller('createworkshopController', function($scope, $http) {
$http.get(end_url + ':' + port + '/createworkshop')
.success(function(data) {
$scope.form = data.Workshop;
});
$scope.submitWorkshop = function() {
};
});
Here is a picture of what the html look like right now, The form title is passed in easily.
Please help me! I'm still learning! Thanks!!!
$http({ method: 'POST', data: $scope.result.form, url: 'path/to/api' })
This will send JSON data of the $scope.result.form object to the required API URL.

Error in ajax call using angular js

I am new to angular js .I tried making a small program that consists of ajax call using angular js $http .I guess I am some where wrong ,doing some mistake.
Would be happy If someone helps out. Following is code snippet
login.html
<head></head>
<body>
<form ng-app="" ng-controller="validateCtrl" name="myForm" novalidate>
<div ng-hide="var">
<h2><center>SIGN-IN</center></h2>
<p>Username:
<br>
<input type="text" name="user" ng-model="user" required><span style="color:red" ng-show="myForm.user.$error.required" />Username is required</p>
<p>Password:
<br>
<input type="password" name="password" ng-model="password" required /> <span style="color:red" ng-show="myForm.password.$error.required">Password is required.</span>
<p>
<input type="submit" ng-click="validate()" ng-disabled=" myForm.user.$invalid ||
myForm.password.$invalid" />
</p>
</div>
<div ng-hide="welcomeVar"> <span> {{ listOfCustomers }} </span>
<h2><center>Welcome! {{ user }}</center></h2>
<button class="list" ng-click="customerList()">List of Customers</button>
<ul>
<li ng-repeat="x in listOfCustomers">{{ x.CustomerID + ', ' + x.CompanyName }}</li>
</ul>
<br>
<button class="signout" ng-click="validate()">Log Out</button>
</div>
</form>
JS part:
<script>
function validateCtrl($scope, $http) {
$scope.user = 'ABC XYZ';
$scope.password = 'abcbc';
$scope.welcomeVar = true;
$scope.
var = false;
$scope.validate = function() {
$scope.
var = !$scope.
var;
$scope.welcomeVar = !$scope.welcomeVar
};
$scope.listOfCustomers = null;
$scope.customerList = function() {
$http.get("http://www.iNorthwind.com/Service1.svc/getAllCustomers")
.success(function(data) {
$scope.listOfCustomers = data;
})
.error(function(data) {
$scope.user = 'Xyz';
});
};
}
</script>
Your code is fine, except some syntax errors, but I hope it's because you tried to remove somrthing before posting code here ;)
Also the response for your request have this structure: {GetAllCustomersResult : [//here an array of elements]} , so, in success response handler you'll have to do: $scope.listOfCustomers = data.GetAllCustomersResult ;
But it's a minor things, the main issue described here:
AngularJS performs an OPTIONS HTTP request for a cross-origin resource
To debug this, you had to open developer tools in any browser('F12' is common key to open it), and look in console and network requests.

Convert user input into a label using angular.js

What I'am trying to do is convert every user input into a label using angular. I believe that I'am doing the right thing, but is not working. I will appreciate if somebody take a look at this code. Thank you
here is a plunker
<div class="row" ng-controller="tagForm">
<div ng-click="addEntry()">
<div class="col-xs-12 col-sm-12 col-md-10 ">
<input type="text" placeholder="What are your area of expertise" ng-model="newEntry.name" class="form-control border" />
</div>
<div class="col-xs-12 col-md-2 center form-button">
<input type="button" value="Add" class="btn btn-orange btn-add" />
</div>
<div class="col-md-8 col-sm-offset-2" id="up">
<br />
<span class="label label-primary" ng-repeat="entry in entries">{{entry.name}}</span>
</div>
</div>
</div>
app.controller('tagForm', ['$scope', function($scope) {
return $scope.addEntry = function() {
$scope.entries.push($scope.newEntry);
return $scope.newEntry = {};
};
}]);
You have a few things wrong in your Plunk, but here's some stuff to start with:
You need to wire up a click event on your Add button. Right now, its not doing anything when you click it
Bind to an ng-model on the scope just using 'newEntry'. All you're typing is a name so thats all you need to save on the scope.
Loop over entries, printing out just 'entry' instead of 'entry.name'
And your controller should look like this (no need for the returns)
app.controller('tagForm', ['$scope', function($scope) {
$scope.entries = [];
$scope.addEntry = function() {
$scope.entries.push($scope.newEntry);
};
}]);
See this fiddle:
http://jsfiddle.net/smaye81/anrv2qms/1/

Resources