How to send value of dropdown in backend in angularjs? - angularjs

I am using Spring + AngularJS. How to send value of dropdown in backend in angularjs?
HTML:
<div class="col-md-4">
<select ng-model="algoList">
<option ng-repeat="algo in algoList" value="{{algo}}">{{algo}}</option>
</select>
<button class="btn btn-primary" ng-click="applyAlgo()">
<span class="glyphicon glyphicon-right"></span> Apply
</button>
</div>
JS:
$scope.algoName = "";
$scope.algoList= ["DC_CleaningOperations","FilerOperation"];
$scope.applyAlgo = function() {
var response = $http.post('/idw-dv/getAlgo', $scope.algoName);
response.success(function(data, status, headers, config) {
swal("Following algorithm is applied successfully. :",data,"success");
console.log(data);
});
response.error(function(data, status, headers, config) {
swal( "Exception details: " + JSON.stringify({data: data}));
});
Controller:
#RequestMapping(value = "/getAlgo", method = RequestMethod.POST)
#ResponseBody
public String getAlgorithm(#RequestBody String algoName) {
return algoName;
}

So here was the problem, the model you defined for select field is wrong and will eventually lead you to problem.
The selected value from dropdown will now be stored in algoName if you change the ng-model to "algoName".
This value will now be transferred to Spring Controller as a String.
Hope this works...
<div class="col-md-4">
<select ng-model="algoName">
<option ng-repeat="algo in algoList" value="{{algo}}">{{algo}}</option>
</select>
<button class="btn btn-primary" ng-click="applyAlgo()">
<span class="glyphicon glyphicon-right"></span> Apply
</button>
</div>

Related

model does not change angularjs

I have client list in a table.
When I click on editClient, the name of the client will be displayed in an input text. This work perfectly.
<body ng-app="myClientApp" ng-controller="myClientController">
<a class="btn btn-success" ng-click="chargerClients()">
Charger Clients
</a>
<div ng-if="clients">
<table>
<tr ng-repeat="cl in clients >
<td>{{cl.idClient}} </td>
<td>{{cl.nomClient}} </td>
<td> <a class="btn btn-success" ng-click="editClient(cl.idClient,cl.nomClient)"></td>
</table>
<div>
<input type="text" ng-model="id">
<input type="text" ng-model="nom">
<button ng-click="modifyClient()"> validate</button>
</div>
</div>
</body>
The problem is when I click on modifyClient, it keeps the same values and nothing happens. How can I fix this problem?
<script>
var app=angular.module("myClientApp", []);
app.controller("myClientController", function($scope,$http,$window) {
$scope.chargerClients=function(){
$http.get("/clients")
.success(function(data){
$scope.clients=data;
});
};
//load id and name
$scope.editClient=function(idClient, nomClient){
$scope.id=idClient;
$scope.nom=nomClient;}
//modifyClient
$scope.modifyClient=function(){
var params="";
var params = ({
idClient:$scope.id,
nomClient: $scope.nom});
$http({
method: 'PUT',
url: "clients",
data: params,
headers: {'Content-type': 'application/json'}
})
.success(function(data) {
$window.alert($scope.id+$scope.nom);
$scope.chargerClients();
$window.location.href = '/index.html'
})
};
}
</script>
Try using POST method in your modifyClient
Thank you i solve it; i have to add link in ng-model:
`<ng-model="client.id">`
and in the script also:
$scope.client={}
$scope.editClient=function(idClient, nomClient){
$scope.client.id=idClient;
}
$scope.modifyClient=function(){
var params="";
var params = ({
idClient:$scope.client.id
});

AngularJS Textarea If data Is loading

I have a textarea that relies upon a dropdown menu to populate. When the dropdown is changed, a file is pulled and the contents are loaded to the textarea.
While the textarea is loading, it just says [object Object]. I'd like it to be a bit nicer than that. Something like 'Loading...'.
I cant find away to specifically do this with a textarea though.
Another wrench in the wheel is that the Save functionality actually relies upon the value of the text area to save, so I cant just alter the content of the text area to display 'Saving...' otherwise the content that is written to the file is just 'Saving...'.
Here is the code:
View
<div id="Options" class="panel-collapse collapse">
<div class="panel-body">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon input-sm">Config Select</span>
<select ng-change="update()" ng-model="configFileName" class="form-control input-sm">
<option>--</option>
<option ng-repeat="conf in configList" value="{{conf.name}}">{{conf.name}}</option>
</select>
</div>
</div>
<div class="form-group">
<div class="input-group">
<td style="padding-bottom: .5em;" class="text-muted">Config File</td><br />
<textarea id="textareaEdit" rows="20" cols="46" ng-model="configFileContent"></textarea>
<input type="button" ng-click="updateConfig()" style="width: 90px;" value="Save"></button>
</div>
</div>
</div>
</div>
JS
$scope.update = (function(param) {
$scope.configFileContent = 'Loading...';
$scope.configFileContent = $api.request({
module: 'Radius',
action: 'getConfigFileContent',
method: 'POST',
data: $scope.configFileName
}, function(response) {
$timeout(function() {
console.log('got it');
$scope.configFileContent = response.confFileContent;
}, 2000);
});
});
$scope.updateConfig = (function(param) {
var data = [$scope.configFileName, $scope.configFileContent];
var json = JSON.stringify(data);
$scope.configFileContent = $api.request({
module: 'Radius',
action: 'saveConfigFileContent',
method: 'POST',
data: json
}, function(response) {
$timeout(function() {
console.log('Saved!');
$scope.update();
}, 2000);
});
});
<script>
var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope, $timeout) {
$scope.update = function() {
if ($scope.selectedData === '') {
$scope.someData = '';
return;
}
// do http response
var data = 'dummy file text from server';
$scope.xhr = false;
$scope.msg = 'loading...';
// simulating fetch request
$timeout(function() {
$scope.xhr = true;
$scope.content = data;
}, 3000);
}
});
</script>
<div ng-app="myShoppingList" ng-controller="myCtrl">
<select ng-model="selectedData" ng-change="update()">
<option selected="selected" value="">Select data</option>
<option value="foo">Fetch my data</option>
</select>
<br><br><br>
<textarea rows="5" cols="20" ng-model="someData" ng-value="xhr === false ? msg : content">
</textarea>
</div>
You can use a scope variable to detect the completion of promise request of xhr and simulate a loading... message.
As for save, i recommend not to use such approach of displaying message inside textarea and instead create another directive/component to detect the loading and saving request completion which is reusable and separates business logic keeping controller thin.

angular: form submit with dynamic dropdown list

I have a small form and in that form i have a drop down list. List items are generated dynamically.
$http({
url: 'alljobs.php',
method: "GET",
params: {
uid: viewer_id
}
}).success(function(data) {
$scope.jobss = data.content;
});
Below is the code for form submit.
$scope.formprofile33 = function() {
var allData33 = {
'msg': $scope.msg,
'emp_id': viewer_id,
'job_id': job.job_id,
'job_title': $scope.jobss.SelectedOption.job_title,
// 'job':job,
'user_id': user_id
}
$http({
method: 'POST',
url: 'send_msg.php',
data: allData33,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data) {
if (!data.success) {
$scope.message = data.errors.message;
} else {
$scope.message = '';
alert('Your message has been sent.');
$scope.message = '';
}
});
};
Here is the form.
<form name="formProfile33" method="post" id="formProfile33" role="form" ng-submit="formprofile33()">
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="row">
<div class="col-xs-10">
<div class="col-xs-12 s_ma">
<select id="job" name="job" class="search_color selectors form-control" ng-model="job" required="required" ng-options="item.job_title for item in jobss track by item.job_id">
<option value=""> Select Job *</option>
</select>
</div>
<textarea name="msg" ng-model="msg" class="form-control textbox1" id="msg" placeholder="Write your message" required="required" rows="3"></textarea>
</div>
</div>
</div>
</div>
<center>
<button type="submit" class="btn btn-home" name="btn-save1" id="btn-save1" required="required"><i class="icon ion-email"></i> Send Message </button>
</center>
</div>
</form>
Problem is i am not able to pass dropdown value and id during form submit.
I am getting below error.
TypeError: Cannot read property 'job_title' of undefined
Please advise how can i submit the form with dropdown id and value.
Your example set a job item to the scope field "job" => ng-model="job",
the full selected item is accessible with $scope.job.
Try $scope.job.job_title or $scope.job.job_id
A print out in your html is anytime a good helper: Full job item: {{job | json}}
https://plnkr.co/edit/VenFVchI0brGZNC2Q7Fn?p=preview

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.

AngularJS - Upload Image to SharePoint Library/Corrupted File

I am using the following Angular Module to attempt to upload images to SharePoint through a Web browser: https://github.com/nervgh/angular-file-upload
I am getting successful 200 POST messages and a file is being uploaded... However, it is not showing the image itself in the preview or opening of the image, but rather an [X]. I am guessing this is related to how the content is encoded, but unsure of what to do next. Here is my controller:
appControllers.controller('appUploadImageCtrl', ['$scope', '$location', 'FileUploader', function ($scope, $location, FileUploader) {
var uploader = $scope.uploader = new FileUploader({
url: "/sites/_api/web/lists/getByTitle('Images')/RootFolder/Files/add(url='test.jpg',overwrite='true')",
processData: false,
transformRequest: angular.identity,
headers: {
'Accept': 'application/json;odata=verbose', 'content-type': undefined, 'X-RequestDigest': $("#__REQUESTDIGEST").val() }
});
// FILTERS
uploader.filters.push({
name: 'imageFilter',
fn: function (item /*{File|FileLikeObject}*/, options) {
var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
}
});
// CALLBACKS
uploader.onWhenAddingFileFailed = function (item /*{File|FileLikeObject}*/, filter,
options) {
console.info('onWhenAddingFileFailed', item, filter, options);
};
uploader.onAfterAddingFile = function (fileItem) {
console.info('onAfterAddingFile', fileItem);
};
uploader.onAfterAddingAll = function (addedFileItems) {
console.info('onAfterAddingAll', addedFileItems);
};
uploader.onBeforeUploadItem = function (item) {
console.info('onBeforeUploadItem', item);
};
uploader.onProgressItem = function (fileItem, progress) {
console.info('onProgressItem', fileItem, progress);
};
uploader.onProgressAll = function (progress) {
console.info('onProgressAll', progress);
};
uploader.onSuccessItem = function (fileItem, response, status, headers) {
console.info('onSuccessItem', fileItem, response, status, headers);
};
uploader.onErrorItem = function (fileItem, response, status, headers) {
console.info('onErrorItem', fileItem, response, status, headers);
};
uploader.onCancelItem = function (fileItem, response, status, headers) {
console.info('onCancelItem', fileItem, response, status, headers);
};
uploader.onCompleteItem = function (fileItem, response, status, headers) {
console.info('onCompleteItem', fileItem, response, status, headers);
};
uploader.onCompleteAll = function () {
console.info('onCompleteAll');
};
console.info('uploader', uploader);
$scope.cancel = function () {
$location.path('/');
}
}]);
HTML:
<div class="col-md-3">
<h3>Select files</h3>
<div ng-show="uploader.isHTML5">
<!-- 3. nv-file-over uploader="link" over-class="className" -->
<div class="well my-drop-zone" nv-file-over="" uploader="uploader">
Base drop zone
</div>
<!-- Example: nv-file-drop="" uploader="{Object}" options="{Object}" filters="{String}" -->
<div nv-file-drop="" uploader="uploader" options="{ url: '/foo' }">
<div nv-file-over="" uploader="uploader" over-class="another-file-over-class" class="well my-drop-zone">
Another drop zone with its own settings
</div>
</div>
</div>
<!-- Example: nv-file-select="" uploader="{Object}" options="{Object}" filters="{String}" -->
Multiple
<input type="file" nv-file-select="" uploader="uploader" multiple /><br />
Single
<input type="file" nv-file-select="" uploader="uploader" />
</div>
<div class="col-md-9" style="margin-bottom: 40px">
<h3>Upload queue</h3>
<p>Queue length: {{ uploader.queue.length }}</p>
<table class="table">
<thead>
<tr>
<th width="50%">Name</th>
<th ng-show="uploader.isHTML5">Size</th>
<th ng-show="uploader.isHTML5">Progress</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in uploader.queue">
<td><strong>{{ item.file.name }}</strong></td>
<td ng-show="uploader.isHTML5" nowrap>{{ item.file.size/1024/1024|number:2 }} MB</td>
<td ng-show="uploader.isHTML5">
<div class="progress" style="margin-bottom: 0;">
<div class="progress-bar" role="progressbar" ng-style="{ 'width': item.progress + '%' }"></div>
</div>
</td>
<td class="text-center">
<span ng-show="item.isSuccess"><i class="glyphicon glyphicon-ok"></i></span>
<span ng-show="item.isCancel"><i class="glyphicon glyphicon-ban-circle"></i></span>
<span ng-show="item.isError"><i class="glyphicon glyphicon-remove"></i></span>
</td>
<td nowrap>
<button type="button" class="btn btn-success btn-xs" ng-click="item.upload()" ng-disabled="item.isReady || item.isUploading || item.isSuccess">
<span class="glyphicon glyphicon-upload"></span> Upload
</button>
<button type="button" class="btn btn-warning btn-xs" ng-click="item.cancel()" ng-disabled="!item.isUploading">
<span class="glyphicon glyphicon-ban-circle"></span> Cancel
</button>
<button type="button" class="btn btn-danger btn-xs" ng-click="item.remove()">
<span class="glyphicon glyphicon-trash"></span> Remove
</button>
</td>
</tr>
</tbody>
</table>
<div>
<div>
Queue progress:
<div class="progress" style="">
<div class="progress-bar" role="progressbar" ng-style="{ 'width': uploader.progress + '%' }"></div>
</div>
</div>
<button type="button" class="btn btn-success btn-s" ng-click="uploader.uploadAll()" ng-disabled="!uploader.getNotUploadedItems().length">
<span class="glyphicon glyphicon-upload"></span> Upload all
</button>
<button type="button" class="btn btn-warning btn-s" ng-click="uploader.cancelAll()" ng-disabled="!uploader.isUploading">
<span class="glyphicon glyphicon-ban-circle"></span> Cancel all
</button>
<button type="button" class="btn btn-danger btn-s" ng-click="uploader.clearQueue()" ng-disabled="!uploader.queue.length">
<span class="glyphicon glyphicon-trash"></span> Remove all
</button>
</div>
</div>
The problem with your code is that you are trying to upload your image as a normal byte array, which isn't possible when you are uploading to libraries through the SharePoint REST API.
To be able to upload non-text files to SharePoint, they have to be uploaded as a base64 encoded byte array.
Your options are to either use another Angular module such as Angular-Base64-Upload, or to encode the image file before you upload it using your first choice of file upload module.
In case you go for option two, you can encode the image using the following technique, though how it will work with your selected file uploader, I cannot say. It appears you can modify the file attribute of the FileItem in the file uploader, so it should not be that hard.
Encoding the image file to a base64 binary arraybuffer
//Create a new FileReader object
var reader = new FileReader();
reader.onload = processImage;
//Read the file as a base64 encoded string
reader.readAsDataURL(input.files[0]);
function processImage () {
//The image file has been read by the filereader
//and can be converted to an arraybuffer
var arrayBuffer = base64ToBinary(this.result);
//Upload the image to the SharePoint images library
uploadImage(arrayBuffer);
}
function base64ToBinary (base64EncodedFile) {
var BASE64_MARKER = ';base64,';
var base64Index = base64EncodedFile.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = base64EncodedFile.substring(base64Index);
var raw = atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(rawLength);
for (i = 0; i < rawLength; i++)
{
array[i] = raw.charCodeAt(i);
}
return array.buffer;
}
When I wrote a similar piece of code for a project, I noticed that SharePoint (or just IE) had trouble getting the MIME types correct. I ended up stripping it from the image to make it work, as below.
var raw = atob(base64.replace(/^data:image\/(png|jpg);base64,/, ""));
Uploading to SharePoint image library using the REST API and Ajax
If you decide to not go for an Angular module to upload your file, you can instead upload files directly to a SharePoint library through the REST API using normal ajax calls with jQUery. This might have to be modified for the Angular syntax, but the concept is the same.
var requestUrl = String.format("{0}/_api/web/lists/getByTitle('Images')/rootfolder/files/Add(url='{1}', overwrite=true)", _spPageContextInfo.siteAbsoluteUrl, fileName);
$.ajax({
url: requestUrl,
type: "POST",
data: buffer, //This is the base64 encoded buffer from the above step
processData: false,
headers: {
Accept: "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function(result) {
console.log("Upload complete!");
},
error: function(error) {
console.log("Something went wrong!");
}
});

Resources