Bind TextBox, date and dropdownlist value to parameter angularJS wcfRest - javascript

I have an angularJS using WCFrest Project
I create dropdownlist and datepicker for parameter to filter showed data.
Search Form can be seen on picture below
This is the html code
<!--Date From-->
<div class="col-md-4">
<input id="txtOldDate" type="date" value="2000-01-01" class="datepicker" />
</div>
<!--Date To-->
<div class="col-md-1">
<label for="labelTo" class="control-label">To</label>
</div>
<div class="col-md-4">
<input id="txtNewDate" type="date" class="datepicker" />
<!-- Set default date value to now-->
<script>
document.getElementById('txtNewDate').value = new Date().toISOString().substring(0, 10);
</script>
</div>
<!--Departement-->
<div class="col-sm-4">
<div class="dropdown">
<select class="form-control" ng-model="DdlDeptManager" ng-change="DdlManager(DdlDeptManager)">
<option ng-repeat="d in GetDeptManager" value="{{d.Department}}">{{d.Department}}</option>
</select>
</div>
</div>
<!--Employee-->
<div class="dropdown">
<!-- #departemen parameter from DdlDeptManager -->
<select id="ddlManagerApproval" ng-model="DdlManager" class="form-control">
<option ng-repeat="m in GetManager" value="{{m.UserName}}">{{m.FullName}}</option>
</select>
</div>
<!--Button Show-->
<div class="col-md-2">
<input id="btnSubmit" type="button" class="btn btn-primary" ng-click="SearchApproval()" value="Show" />
</div>
This is my control approvalCtrl.js
//Control for search purposes
$scope.SearchApproval = function() {
var search = {
//employeeID: $scope.employeeID,
oldDate: $scope.oldDate,
newDate: $scope.newDate,
departemen: $scope.departemen,
approver: $scope.approver
}
var promiseGet = GetApproval.GetApprovalData(search);
//GetApprovalData();
promiseGet.then(function(pl) {
$scope.GetApprovalData = pl.data
},
function(errorPl) {
console.log('Some Error in Getting Records.', errorPl);
});
}
This is the service.js, for employeeID because the session is not created, i forced add value to it on the uri
this.GetApprovalData = function(employeeID, oldDate, newDate, departemen, approver) {
return $http.get("http://localhost:51458/ServiceRequest.svc/GetApproval?employeeID=" + "11321" + "&oldDate=" + oldDate + "&newDate=" + newDate + "&departemen=" + departemen + "&approver=" + approver);
};
My Question is, how to make the value on datepicker id = txtOldDate to give a paramater value to oldDate, txtNewDate to newDate, and other dropdownlist to departemen and approver parameter?
Thanks in Advance.

Hi Randy I have reproduced your code without service sorry for that. Used hardcode array to populate dropdown. Kindly check this url
https://plnkr.co/edit/eSriV68HkhQhzt1yE6DE?p=preview
$scope.GetDeptManager = [{
Department : 'department1'
}, {
Department: 'department2'
}];
$scope.GetManager = [{
FullName : 'manager1'
}, {
FullName: 'manager2'
}]
And you have to assign ng-model values for your input elements so that you will get those values in controller.

Related

jQuery: Conflict with removeData() executing at inadequate times

I have a modal window used to update or add a new object Store.
This modal is called remotely which information is loaded from a GET method constructed in ASP.NET.
Button that calls the modal:
<div class="btn-group" id="modalbutton">
<a id="createEditStoreModal" data-toggle="modal" asp-action="Create"
data-target="#modal-action-store" class="btn btn-primary">
<i class="glyphicon glyphicon-plus"></i> NEW STORE
</a>
</div>
Html of the modal:
#model Application.Models.ApplicationviewModels.StoreIndexData
#using Application.Models
<form asp-action="Create" role="form">
#await Html.PartialAsync("_ModalHeader", new ModalHeader
{ Heading = String.Format("ActualizaciĆ³n de Modelo: Tiendas") })
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="modal-body form-horizontal">
<div class="form-group">
<label asp-for="DepartmentID" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="DepartmentID" class="form-control"
asp-items="#(new SelectList(#ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Distrito</label>
<div class="col-md-10">
<select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
asp-items="#(new SelectList(#ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>
</div>
</div>
{... more elements}
</div>
</form>
GET Method:
public IActionResult Create(int? id)
{
List<Department> DepartmentList = new List<Department>();
DepartmentList = (from department in _context.Departments
select department).ToList();
DepartmentList.Insert(0, new Department { DepartmentID = 0, DepartmentName = "-- Seleccione Departamento --" });
ViewBag.ListofDepartment = DepartmentList;
StoreIndexData edit = new StoreIndexData();
List<District> ListofDistrict = new List<District>();
ListofDistrict.Insert(0, new District { DistrictID = 0, DistrictName = "-- PRUEBA --" });
ViewBag.ListofDistrict = ListofDistrict;
return PartialView("~/Views/Shared/Stores/_Create.cshtml");
}
The problem:
I have the following jQuery which asigns a value to DistrictID once the modal opens:
<script type="text/javascript">
var wasclicked = 0;
var $this = this;
$(document).ready(function () {
document.getElementById("modalbutton").onclick = function () {
//is AddNew Store button is hitted, this var = 1
wasclicked = 1;
};
$('#modal-action-store').on('hidden.bs.modal', function () {
//global.wasclicked = 0;
wasclicked = 0;
$(this).removeData('bs.modal');
});
$('#modal-action-store').on('shown.bs.modal', function (e) {
console.log($('#DistrictID').length);
//if wasclicked equals 1 that means we are in the AddNew Store scenario.
if (wasclicked == 1) {
//a default value is sent to District dropdownlist
var items = "<option value='0'>-- Seleccione Distrito --</option>";
$('#DistrictID').html(items);
};
});
});
</script>
The problem right now is that after this line jQuery is executed, the value that was assigned to DistrictID gets overwritten by :
ViewBag.ListofDistrict = ListofDistrict; //"-- PRUEBA --"
And this line is lost:
var items = "<option value='0'>-- Seleccione Distrito --</option>";
What I suspect is that the information coming from the Controller overwrites any result from jQuery over the in the modal.
After debugging I have identified three diferent moments:
Moment 1: First time we open the modal
The modal hasn't opened yet and the jQuery executes
For this reason it does not identify DistrictID
The result from the GET Action fills the modal's inputs.
Moment 2 - Part 1: Second time we open the modal
This time the modal opens before the jQuery is executed
The DistrictID has the value from the GET Method before we assign the value from jQuery
Moment 2 - Part 2: When the value from jQuery is assigned
The value from jQuery is assigned to DistrictID
This value will be overwritten by the result of the GET Action
Question:
Can anyone explain or help me understand what might be causing this? What else can I do to identify the reason behind this?
Trying moving the assigning of html to districtID from your main view to the document.ready of modal popUp view.
#model Application.Models.ApplicationviewModels.StoreIndexData
#using Application.Models
<form asp-action="Create" role="form">
#await Html.PartialAsync("_ModalHeader", new ModalHeader
{ Heading = String.Format("ActualizaciĆ³n de Modelo: Tiendas") })
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="modal-body form-horizontal">
<div class="form-group">
<label asp-for="DepartmentID" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="DepartmentID" class="form-control"
asp-items="#(new SelectList(#ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Distrito</label>
<div class="col-md-10">
<select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
asp-items="#(new SelectList(#ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>
</div>
</div>
{... more elements}
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
//if wasclicked equals 1 that means we are in the AddNew Store scenario.
if (wasclicked == 1) {
//a default value is sent to District dropdownlist
var items = "<option value='0'>-- Seleccione Distrito --</option>";
$('#DistrictID').html(items);
}
});
</script>
PS: Default option can be also be used. refer the below code.
<div class="form-group">
<label class="col-md-2 control-label">Distrito</label>
<div class="col-md-10">
<select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID" asp-items="#(new SelectList(#ViewBag.ListofDistrict,"DistrictID","DistrictName"))">
<option value='0'>-- Seleccione Distrito --</option>
</select>
</div>
</div>
modal() only accepts an options object or a string. To append elements to your modal, we can append them when the show.bs.modal is triggered:
$('#modal-action-store').on('show.bs.modal', function(e){
var items = "<option value='0'>-- Seleccione Distrito --</option>";
$('#DistrictID').html(items);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="btn-group" id="modalbutton">
<a id="createEditStoreModal" data-toggle="modal" asp-action="Create"
data-target="#modal-action-store" class="btn btn-primary">
<i class="glyphicon glyphicon-plus"></i> NEW STORE
</a>
</div>
<div class="modal" id="modal-action-store">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<select class="form-control" id="DistrictID" name="DistrictID">
</select>
</div>
</div>
</div>
</div>
I would update your http://plataformafantasypark.azurewebsites.net/Stores/create to contain <option value='0'>-- Seleccione Distrito --</option> by default. This would limit the options to overwrite the element with zero entries.
This would make your js code easier too.
By the way, why do you use document.getElementById("modalbutton").onclick when you can use $("#modalbutton").on("click", function(){}); because you are using jQuery for everything else.

How to Pass id and name from the first form, and Show only the name in second form in angularjs

I Have two forms.In these forms am getting input from the first form and show that in the second form, Which means if the user selected the currency from the dropdown, i need to pass id and the the currency name. But show only the currency name in the second form. I tried one method (dont know whether it is correct or not) it is showing the id only. am new to angular. is there anyway to solve this?
HTML
<div class="row text-center" ng-show="firstform">
<form name="validation">
<label>Currency</label>
<select ng-model="CurrencyId" ng-selected="CurrencyId" class="form-control" id="CurrencyId">
<option ng:repeat="CurrencyId in currencyList" ng-selected="selectedCurrencyType == CurrencyId.id" value={{CurrencyId.currencyId}}>{{CurrencyId.name}}</option>
</select>
<label>Grade</label>
<select ng-model="GradeId" ng-selected="GradeId" class="form-control" id="GradeId">
<option ng:repeat="GradeId in RaceGradeList" ng-selected="selectedGrade == GradeId.id" value={{GradeId.id}}>{{GradeId.gradeName}}</option>
</select>
<button type="submit"value="add" ng-click="savedetails()" />
</form>
</div>
<div class="row text-center" ng-show="secondform">
<form name="thirdform">
<ul >
<li><p>Currency:{{CurrencyId}}</p> </li>
<li><p>Grade:{{GradeId}}</p> </li>
</ul>
</form>
</div>
angular controller
$scope.savedetails = function () {
$scope.firstform= false;
$scope.secondform = true;
}
This is the most simplest solution that you can go for. Instead of having the value={{CurrencyId.currencyId}} set it as value={{CurrencyId.name}} for the options in the dropdown and you are good to go. Below is the demo for the same. But if you want to save currencyId as the value then you will have to iterate over the array and find the name based on the selected currencyId and then show that in the view.
UPDATE
Updated the code to have the currencyId being stored as the selected value and then based on that showing the name in the view.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.currencyList = [{
currencyId: 1,
name: "INR"
},
{
currencyId: 2,
name: "$"
},
{
currencyId: 3,
name: "#"
}
];
$scope.currencyChanged = function() {
var selectedCurrency;
for (var i = 0; i < $scope.currencyList.length; i++) {
var thisCurr = $scope.currencyList[i];
if ($scope.CurrencyId == thisCurr.currencyId)
selectedCurrency = thisCurr.name;
}
return selectedCurrency;
}
$scope.firstform = true;
$scope.savedetails = function() {
$scope.firstform = false;
$scope.secondform = true;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<div class="row text-center" ng-show="firstform">
<form name="validation">
<label>Currency</label>
<select ng-model="CurrencyId" ng-selected="CurrencyId" class="form-control" id="CurrencyId">
<option ng:repeat="CurrencyId in currencyList" ng-selected="CurrencyId == CurrencyId.currencyId" value={{CurrencyId.currencyId}}>{{CurrencyId.name}}</option>
</select>
<button type="button" value="add" ng-click="savedetails()">Save Details</button>
</form>
</div>
<div class="row text-center" ng-show="secondform">
<form name="thirdform">
<ul>
<li>
<p>Currency:{{currencyChanged()}}</p>
</li>
</ul>
</form>
</div>
</body>
Hope it helps :)
You can use ng-options , its very flexiable where we can display one value and select either entire object or any specific property.
Please check below plunker , hope it meets your requirement
https://plnkr.co/edit/JQjmAwk62R8rfAlTZ696?p=preview
<select ng-model="CurrencyId" ng-options="currency.id for currency in currencyList" class="form-control" id="CurrencyId" >
</select>
For more details on ng-options , go through below video
https://www.youtube.com/watch?v=vqx3zCy4d3I
try
<li><p>Currency:{{CurrencyId.name}</p> </li>

how to display selected value of dropdown in input text fields in angular js

html file:
<select ng-model="shipping" ng-options="shipping.shipping for shipping in shipAddress">
<option value=''>--Select Address --</option>
</select>
<form name="shippingForm" class="form-horizontal" role="form">
<div class="form-group">
<p class="control-p col-sm-2" for="Address">Address Line1</p>
<div class="col-sm-10">
<input type="text" name="Address" placeholder="Address Line1"
ng-model="shipping.addressLine1" class="input-width" ng-init ="shipping.addressLine1"/>
</div>
</div>
<div class="form-group">
<p class="control-p col-sm-2" for="Address2">Address Line2:</p>
<div class="col-sm-10">
<input type="text" name="AddressLine" placeholder="Address Line2" ng-model="shipping.addressLine2" class="input-width" />
</div>
</div>
</form>
js file:
if (data){
console.log(data);
$scope.addressToShip = data;
var ShipAddress=[];
storeLocally.set('ship Info', data);
if(data.addressLine2 == null){
$scope.shipAddress = data.map(function(address) {
return {
shipping: address.addressLine1
};
});
}
else{
$scope.shipAddress = data.map(function(address) {
return {
shipping: address.addressLine1 +', '+ address.addressLine2
};
});
}
}
},
function (data) {
//if (data.status == 500) {
// $scope.addressError = "Oops! No Address Found!";
};
data:
{0 :"123 waller st,suite#220"},
{1 :"323 waller st,suite#230"}
The problem is the form I am using intially to save data. Once data is saved to db it is coming in dropdown. After choosing one value from dropdown it should come to text fields.
I have tried so far ng-model by using same variable names,even though form's ng-model and dropdown's ng-model have same variable i.e. shipping.. But it didn't work. Please help me out what I am missing in here.
If I understand your goal and you data's schema, you need to change the ng-model of the input[name="Address"] to shipping.addressLine1.shipping.
I get this idea according the data's structure that came from the .map:
return {
shipping: address.addressLine1
};
You can see the structure when you pick a option from the select - the model will displayd and you can see that the structure is (for example):
{
"addressLine1": {
"shipping": "123 waller st"
}
}
If you have a question about this, let me know.
I tried to simulate the situation without the server, hopefully I simulate it right.
Now, to the code:
angular.module('myApp', []).
controller('ctrl', function($scope) {
var data = [{
addressLine1:"123 waller st", addressLine2:"suite#220"
}];
if (data) {
console.log(data);
$scope.addressToShip = data;
var ShipAddress = [];
//storeLocally.set('ship Info', data);
if (data.addressLine2 == null) {
$scope.shipAddress = data.map(function(address) {
return {
shipping: address.addressLine1
};
});
}
else {
$scope.shipAddress = data.map(function(address) {
return {
shipping: address.addressLine1 +', '+ address.addressLine2
};
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ctrl">
<select ng-model="shipping.addressLine1" ng-options="shipping.shipping for shipping in shipAddress">
<option value=''>--Select Address --</option>
</select>
<br />
<pre>
{{shipping | json}}<br />
{{shipping.addressLine1 | json}}
</pre>
<form name="shippingForm" class="form-horizontal" role="form">
<div class="form-group">
<p class="control-p col-sm-2" for="Address">Address Line1</p>
<div class="col-sm-10">
<input type="text" name="Address" placeholder="Address Line1"
ng-model="shipping.addressLine1.shipping" class="input-width" ng-init ="shipping.addressLine1"/>
</div>
</div>
<div class="form-group">
<p class="control-p col-sm-2" for="Address2">Address Line2:</p>
<div class="col-sm-10">
<input type="text" name="AddressLine" placeholder="Address Line2" ng-model="shipping.addressLine2" class="input-width" />
</div>
</div>
</form>
</div>
Did you try using AngularJS' ng-change attribute in the drop down?
Try like this:
<select ng-model="shipping" ng-options="shipping.shipping for shipping in shipAddress" ng-change="someFunction(shipping.shipping)">
<option value=''>--Select Address--</option>
</select>
In your controller add the following function:
$scope.someFunction = function(shipping) {
$scope.shipping.addressLine1 = // Assign value from the shipping variable here
$scope.shipping.addressLine2 = // Assign value from the shipping variable here
}
Hope this helps!
Here is a working jsFiddle https://jsfiddle.net/ashishU/umn8or3g/1/

Getting data from the server and using ng-options in select control is failing to show options

this my HTML
<div ng-app="timeTable" ng-controller="addCoursesCtrl">
<button class="btn btn-primary" ng-click="addNewCourse()">Add New Course</button><br/><br/>
<fieldset ng-repeat="choice in choices">
<div class="row">
<div class="col-md-6">
<select class="form-control" ng-model="choice.type" ng-options="s for s in coursetoAdd">
<option value="{{s.shortCut}}">{{s.name}}</option>
</select>
</div>
<div class="col-md-6">
<input type="text" placeholder="Enter Course Name" name="" class="form-control" ng-model="choice.course"/>
</div>
</div>
<br/>
</fieldset>
<button class="btn btn-primary" ng-click="convertAndSend()">Submit</button>
</div>
this the js
var timeTable = angular.module("timeTable",[]);
timeTable.controller("addCoursesCtrl", function ($scope,$http) {
$scope.choices = [{ course: '', type: '' }];
$scope.coursetoAdd ;
$http.get("/Semster/getSuggtedCourses").then(function (response) {
$scope.coursetoAdd = response.data;
});
$scope.addNewCourse = function () {
var newITemNo = $scope.choices.length + 1;
$scope.choices.push({ course: '', type: '' });
};
$scope.convertAndSend = function () {
var asJson = angular.toJson($scope.choices);
console.log(asJson);
$http.post('/Semster/Add', asJson);
};
});
this code bind an object {"course":...,"type":....} every time you click on add course ,and add input field dynamically , my problem is with select control,I'm getting the data from server and use it with ng-optin ,but all it shows it's just [object Object] in select option not the real value.
Assuming that the data returned from getSuggestedCourses is an array of objects, the ng-options selector:
s for s in courseToAdd
will bind s to each object in the array. You need to bind to the fields in the object like this
s.value as s.name for s in courseToAdd

How To pass the modified data from dual listbox to controller?

I have created a form with two listboxes in which it is possible to move the items from one listbox into another.
The view also loads correctly, but I haven't figured out how to send the modified listbox data back to controller.
The view code is the following:
<script>
$(function() {
$(document)
.on("click", "#MoveRight", function() {
$("#SelectLeft :selected").remove().appendTo("#SelectRight");
})
.on("click","#MoveLeft", function() {
$("#SelectRight :selected").remove().appendTo("#SelectLeft");
});
});
#Html.Hidden("RedirectTo", Url.Action("UserManagement", "Admin"));
<h2>User</h2>
<div class="container">
<form role="form">
<div class="container">
<div class="row">
<div class="col-md-5">
<div class="form-group">
<label for="SelectLeft">User Access:</label>
<select class="form-control" id="SelectLeft" multiple="multiple" data-bind="options : ownership, selectedOptions:ownership, optionsText:'FirstName'">
</select>
</div>
</div>
<div class="col-md-2">
<div class="btn-group-vertical">
<input class="btn btn-primary" id="MoveLeft" type="button" value=" << " />
<input class="btn btn-primary" id="MoveRight" type="button" value=" >> " />
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<label for="SelectRight">Owners:</label>
<select class="form-control" multiple="multiple" id="SelectRight" multiple="multiple" data-bind="options : availableOwners, selectedOptions:availableOwners, optionsText:'FirstName'">
</select>
</div>
</div>
</div>
</div>
</form>
</div>
<script>
var data=#(Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)));
var selectedOwners = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.AccessOwners));
var availableOwners = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.Owners));
function viewModel() {
this.username=ko.observable(data.Username);
this.password=ko.observable(data.Password);
this.email=ko.observable(data.Email);
this.isActive=ko.observable(data.IsActive);
this.userId = ko.observable(data.UserId);
this.ownership=ko.observableArray(selectedOwners);
this.availableOwners = ko.observableArray(availableOwners);
this.submit = function()
{
$.ajax({
url: '#Url.Action("UserSave", "Admin")',
type: 'POST',
data: ko.toJSON(this),
contentType: 'application/json',
});
window.location.href = url;
return false;
}
this.cancel = function()
{
window.location.href = url;
return false;
}
};
ko.applyBindings(new viewModel());
var url = $("#RedirectTo").val();
I would be very thankful if anyone could suggest the way to pass all the selected options back to controller by populating the data with modified lists when the submit function is executed.
Thanks!
Before form submission save one side items values in an hidden input element. (comma separated values of listbox items.) The value of hidden element is sent to server by submitting the form. In controller you can do the next things.

Categories