Display selected option in drop down using angular - angularjs

I have one form and am getting values for this form ,from loadEditLevDetails function.
I have binded all the field values except leave type field,I don't knwo how to bind it.
One more thing when I click edit button I can able to change the field values and I can choose some other drop down option,for that I am loading data from getLeaveTypeList method.Based on selected option available leaves field will be auto populated.
<body ng-app="intranet_App" ng-controller="myCtrl" ng-init="init()">
<div class="container">
<form id="row editLeaveDetails" ng-repeat="data in leaveDetails">
<div>
<label>Leave Applied On</label>
<input type="text" name="" ng-model="data.From | date : 'dd/MM/yyyy' ">
</div>
<div>
<label>Leave Type</label>
<select type="text" name="" class="col-xs-12 form-control rField" id="levType" ng-model="data.Leave_type_id" ng-blur="leaveBalance(data.Leave_type_id)"><option value="" selected="selected">Select</option><option data-ng-repeat="data in leaveTypes" value="{{data.id}}">{{data.Name}}</option></select>
</div>
<div>
<label>Availabe Leaves</label>
<input type="text" name="" id="levTaken" >
</div>
<div>
<label>Date From</label>
<input type="text" id="levFrom" onfocus="(this.type='date')" ng-model="data.From | date : 'dd/MM/yyyy' ">
</div>
<div>
<label>Date To</label>
<input type="text" id="levTo" onfocus="(this.type='date')" ng-model="data.To | date : 'dd/MM/yyyy'" >
</div>
<div>
<label>Duration</label>
<input type="text" id="levDuration" ng-model="data.Duration">
</div>
<div>
<label>Reason</label>
<textarea id="LevReason" ng-model="data.Note"></textarea>
</div>
<div class="row pull-right ">
<button class="btn btn-warning editLevDetails btnLeft" ng-click="editDetails()" ng-if="!editMode">Edit</button>
</div>
</form>
</div>
</body>
<script>
var app=angular
.module('intranet_App', [])
.controller('myCtrl', function ($scope, $http) {
$scope.editMode = false;
$scope.init = function () {
$scope.loadLeaves();
$http.post("/leave/getLeaveTypeList").then(function (response) {
$scope.leaveTypes = response.data;
})
}
$scope.loadEditLevDetails = function (id) {
$scope.Id = { leaveRequestId: id };
console.log($scope.Id)
var requestHeaders = {
'content-type': 'application/json'
}
var httpRequest = {
method: 'post',
url: "/leave/editLeaveRequest",
headers: requestHeaders,
data: $scope.Id
}
$http(httpRequest).then(function (response) {
$scope.leaveDetails = response.data;
console.log($scope.leaveDetails)
})
}
$scope.leaveBalance = function (selectedvalue) {
$scope.leaveTypeId = { leaveTypeId: selectedvalue };
var requestHeaders = {
"content-type": 'application/json'
}
var httpRequest = {
method: 'POST',
url: '/leave/getLeaveBalenceCount',
headers: requestHeaders,
data: $scope.leaveTypeId
}
$http(httpRequest).then(function (response) {
$scope.noOfValues = response.data;
$scope.balanceCount = $scope.noOfValues[0].balance_count;
})
}
})
</script>
Please let me know anyone,how to display selected option in dropdown? This is my leaveTypes json.

Try use ng-options directive.
<select ng-model="data.Leave_type_id"
ng-options="leaveType.id as leaveType.name for leaveType in leaveTypes">
<option>Select</option>
</select>

There are two ways you can achieve this :
1. You can add a property name as selected in each object and mark one of them is true which you want to pre-populated in the dropdown.
DEMO
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) {
$scope.leaveTypes = [{
id: 1,
Name: 'Casual Leave',
Selected: false
}, {
id: 2,
Name: 'National Leave',
Selected: true
}, {
id: 3,
Name: 'Regional Leave',
Selected: false
}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp" ng-controller="MyController">
<label>Leave Type</label>
<select type="text" name="" class="col-xs-12 form-control rField" id="levType">
<option value="0">Select</option>
<option data-ng-repeat="data in leaveTypes" value="{{data.id}}" ng-selected="{{ data.Selected == true }}">{{data.Name}}</option>
</select>
</div>
You can assign a selected value into the ng-model of the select element.
DEMO
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) {
$scope.leaveTypes = [{
"id": "1",
Name: 'Casual Leave'
}, {
"id": "2",
Name: 'National Leave'
}, {
"id": "3",
Name: 'Regional Leave'
}];
$scope.selected = {"id": "2"};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="MyApp" ng-controller="MyController">
<label>Leave Type</label>
<select type="text" name="" class="col-xs-12 form-control rField" id="levType" ng-model="selected.id">
<option value="0">Select</option>
<option data-ng-repeat="data in leaveTypes" value="{{data.id}}">{{data.Name}}</option>
</select>
</div>

Related

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.

How to get selected option value from dropdown using angular

I have two drop downs with add resource button, when I click add resource button I need to pass selected option values from drop downs into insertResource method.How to get selected option value??I know we can easily do it using option:selected in jquery But I want do it in angular.Any help?
<body ng-app="intranet_App" ng-controller="myCtrl" ng-init="init()">
<div class="container">
<div class="row">
<div>
<label class="displayBlock margin">Project Name</label>
<input type="text" name="name" class="currentProjectName">
</div>
<div>
<label class="displayBlock margin">Resource Name</label>
<select name="ResourceInsert" id="allocateResource"><option data-ng-repeat="data in resourceList" value="{{data.EmpId}}">{{data.ResourceName}}</option></select>
</div>
<div>
<label class="displayBlock margin">Role Name</label>
<select name="ResourceInsert" id="allocateRole"><option data-ng-repeat="data in roleList" value="{{data.RoleId}}">{{data.RoleName}}</option></select>
</div>
</div>
<div class="row">
<button class="btn btn-primary addResource" ng-click="insertResource()">Add Resource</button>
</div>
</div>
</body>
<script>
var app = angular
.module('intranet_App', [])
.controller('myCtrl', function ($scope,$http) {
$scope.init = function () {
$scope.getProjId();
$scope.ResourceJson();
$scope.RoleJson();
}
$scope.getProjId = function () {
var url = document.URL;
var id = decodeURI(/id=([^&]+)/.exec(url)[1]);
var projectName = decodeURI(/val=([^&]+)/.exec(url)[1]);
$('.currentProjectName').val(projectName)
}
$scope.ResourceJson = function () {
$http.post('/Project/empList').then(function (response) {
$scope.resourceList = response.data;
console.log($scope.resourceList)
})
}
$scope.RoleJson = function () {
$http.post('/Project/roleList').then(function (response) {
$scope.roleList = response.data;
console.log($scope.roleList)
})
}
$scope.insertResource = function () {
}
});
</script>
If your questions is getting data of selected item of select. It is done as follows using ng-model directive:
<select name="ResourceInsert" id="allocateResource" ng-model="selectedValue">
<option data-ng-repeat="data in resourceList" value="{{data.EmpId}}">{{data.ResourceName}}</option>
</select>
In Controller:
console.log($scope.selectedValue, "selected Value"); //Your selected value which is EmpId.

AngularJS: model is not binding

I am using Angular Modal and when I send the input to the modal and set the scope variable, I cannot see the binding happening.
Here is the code:
Note: I am yet to implement the close function in the controller for the modal.
Code for showing the modal:
$scope.approveReq = function (id) {
ModalService.showModal({
templateUrl: "/app/mis/jobno/createjno.html",
controller: "CreateJnoCtrl",
inputs: { input: id }
}).then(function (modal) {
// The modal object has the element built, if this is a bootstrap modal
// you can call 'modal' to show it, if it's a custom modal just show or hide
// it as you need to.
modal.element.modal();
modal.close.then(function (result) {
$scope.message = result ? "You said Yes" : "You said No";
});
});
};
HTML of the modal
<div id="jobcreate" class="modal" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<form name="jobcreate">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Create a new Job</h4>
</div>
<div class="modal-body">
<fieldset class="form-group row">
<label for="iBranchId" class="col-sm-2 form-control-label">Branch</label>
<div class="col-sm-4">
<select class="form-control" ng-required="true" ng-model="jobno.BranchId" id="iBranchId">
<option ng-repeat="b in branches" value="{{b.org_id}}">{{b.org_location}}</option>
</select>
</div>
<label for="iJobType" class="col-sm-2 form-control-label">Job Type</label>
<div class="col-sm-4">
<select class="form-control" style="width:250px" ng-required="true" ng-model="jobno.iJobType" id="iJobType">
<option ng-repeat="jt in jobTypes" value="{{jt.iJobTypeId}}">{{jt.vJobType}}</option>
</select>
</div>
</fieldset>
<fieldset class="form-group row">
<label for="ClieintId" class="col-sm-2 form-control-label">Customer</label>
<div class="col-sm-4">
<select class="form-control" id="ClieintId" ng-required="true" ng-model="selClient" ng-change="getlocs()">
<option ng-repeat="c in clientList" value="{{c.Id}}">{{c.Name}}</option>
</select>
</div>
<label for="vClientLoc" class="col-sm-2 form-control-label">Location</label>
<div class="col-sm-4">
<select class="form-control" id="vClientLoc" ng-required="true" ng-model="jobno.vClientLoc">
<option ng-repeat="l in clientLocs" value="{{l.Loc_Id}}">{{l.Loc_Name}}</option>
</select>
</div>
</fieldset>
<fieldset class="form-group row">
<label for="ContractId" class="col-sm-2 form-control-label">Contract No</label>
<div class="col-sm-4">
<select class="form-control" ng-required="true" ng-model="jobno.ContractId" id="ContractId" ng-options="c.Contract_Id as (c.Contract_No) for c in contracts"></select>
</div>
<div class="col-sm-6" ng-show="createdJobNo">{{createdJobNo}} Created!</div>
</fieldset>
</div>
<div class="modal-footer">
<div class="btn-group">
<button type="button" id="createJobNo" ng-if="!jobcreate.$pristine" ng-disabled="jobcreate.$invalid" class="btn btn-success" ng-click="createJobNo()">Create Job Number</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
</div>
Controller for the modal
angular.module('trg-app.mis').controller('CreateJnoCtrl', ['$http', '$scope', 'ClientDataService', 'input', 'close', function ($http, $scope, ClientDataService, input, close) {
//create Job No
//Get input if any
$scope.jobReq;
//Empty Job
$scope.jobno = {
iJobType: null,
vClientLoc: null,
vJobNo: null,
iRefJobNo: 0,
vRemark: null,
ContractId: 1,
UpdatedBy: 1,
BranchId: null
};
if (input != undefined) {
$scope.jobReq = input;
console.log("Input Received for JobReq: ", input);
$scope.jobno = {
iJobType: $scope.jobReq.Job_Type,
vClientLoc: $scope.jobReq.Client_Location,
vJobNo: null,
iRefJobNo: 0,
vRemark: null,
ContractId: 1,
UpdatedBy: 1,
BranchId: $scope.jobReq.Org_Location
};
}
else {
$scope.jobno = {
iJobType: null,
vClientLoc: null,
vJobNo: null,
iRefJobNo: 0,
vRemark: null,
ContractId: 1,
UpdatedBy: 1,
BranchId: null
};
}
$scope.branches;
$scope.getBranches = function () {
$http.get("/api/orgdetails/").then(
function (resp) {
console.log(resp);
$scope.branches = resp.data;
},
function (err) {
console.log("Error: ", err);
}
);
};
$scope.getBranches();
$scope.jobTypes = {};
$scope.getJobTypes = function () {
console.log("getting Job Types");
$http.get('/api/jobtypes/').then(
function (resp) {
console.log('Response: ', resp);
$scope.jobTypes = resp.data;
},
function (err) {
console.log("Error: ", err);
}
);
};
$scope.getJobTypes();
$scope.clientList;
//get minimal client list and bind to the side bar
$scope.getClients = function () {
ClientDataService.GetClientList()
.then(function (response) {
$scope.clientList = response;
});
};
$scope.getClients();
$scope.clientLocs;
$scope.selClient;
//locs should be brought in when we go to the location editing
$scope.getlocs = function () {
console.log("$scope.selClient: ", $scope.selClient)
if ($scope.selClient != undefined) {
ClientDataService.GetClientLocs($scope.selClient)
.then(function (response) {
$scope.clientLocs = response;
});
$scope.getContracts($scope.selClient);
}
};
//$scope.getlocs();
$scope.contracts;
$scope.getContracts = function (ClientId) {
$http.get('/api/Contracts/client/' + ClientId).then(
function (response) {
$scope.contracts = response.data;
},
function (error) {
console.log("Error getting contracts: ", error);
}
);
};
$scope.createdJobNo;
$scope.createJobNo = function () {
if ($scope.jobno) {
$scope.createdJobNo = null;
console.log($scope.jobno);
$http.post('/api/jobnos/', $scope.jobno).then(
function (response) {
console.log("Job Created: ", response.data.vJobNo);
//$scope.jobno.vJobNo = response.data.vJobNo;
$scope.createdJobNo = response.data.vJobNo;
//TODO: if Job is created from Req, update additional info
//$scope.initJCreate();
},
function (error) {
console.log("Error!");
}
);
}
};
}]);

ng-model data not getting when saving the data

here save the ng-model is newattendance saving to database. "newattendance._id" is not taken as a ng-model.how to make it "newattendance._id" is ng-model
<select class="form-control" ng-options="item.empcode as item.empcode for item in totemplist" ng-model="item.empcode">
</select>
<input type="text" ng-repeat="newattendance in totemplist" ng-model="newattendance._id" ng-show="item.empcode ==newattendance.empcode" style="width:200px;" ><br>
<input placeholder="Enter Attendacne Date" ng-model="newattendance.doa">
<button class="btn btn-primary" ng-click="checkOut()">checkOut</button>
Controller
EmpMasterController.controller("AttendanceController", ['$scope', 'AttendanceFactory',"EmpAddService", function($scope, AttendanceFactory,EmpAddService){
$scope.newattendance={};
$scope.totemplist=EmpAddService.getAllEmpAddItems();
console.log($scope.totemplist);
$scope.checkIn = function(){
AttendanceFactory.addAttendance($scope.newattendance);
$scope.newattendance = {}
}
$scope.getAllAttendance = function(){
console.log("$$$$$"+$scope.newattendance._id)
$scope.attendancedetails =AttendanceFactory.getAllAttendance($scope.newattendance._id);
}
}])
Factory
EmpFactModule.factory("AttendanceFactory", function($resource, RES_URL){
var attendanceResource = $resource(RES_URL+"attandence/:id/:attid",
{"id": "#id", "attid": "#attid"}, {update: {method: "PUT"}})
var attendanceDetails;
return {
addAttendance: function(newattendance){
console.log("..1.. " + newattendance._id)
attendanceResource.save({"id":newattendance._id}, newattendance, function(data){
console.log("Add Success ")
}, function(data, status){
console.log("Add Failed*****");
})
},
getAllAttendance: function(_id){
console.log("..#.. " + _id)
attendanceDetails = attendanceResource.query({"id": _id});
return attendanceDetails;
},
}
})
please help me how make it as ng-model and how to save this...
I've create a JSFiddle for you which hopefully will help you understand the 2 way binding in angular.
you dont need to pass the newattendance object to the check-out function, it is already saved on the scope.
HTML:
<div ng-app="app">
<div ng-controller="formValidation">
<div>
<div>
<span>User Name</span>
<input type="text" placeholder="John" ng-model="newattendance._id">
<span>
<button ng-click="submit()">
check out
</button>
</span>
</div>
</div>
<pre>{{newattendance._id}}</pre>
</div>
</div>
JS:
var app = angular.module('app', []);
app.controller('formValidation', function($scope) {
$scope.submit=function(){
var formPost = {
"Username":$scope.newattendance._id
};
console.log(formPost);
}
});

Passing hidden value in angular

View:
<ul ng-repeat="x in posts.post">
{{x.name}} {{x._id}} {{x.post}} {{x.user_id}}
<br>
<ul ng-repeat="y in x.comment">
{{y.comment}}
</ul>
<input type="text" style="display: none;" ng-model='new_comment.userId' value={{users2.id}} name="userId" >
<input type="text" style="display: none;" ng-model='new_comment.name' value={{users2.name}} name="userName" >
<textarea ng-model='new_comment.comment' name="comment" rows="4" cols="50">
</textarea>
<br>
<input type="submit" value="Post Comment!" ng-click="addComment(x._id, new_comment)">
</ul>
Controller:
UserFactory.getUser(function (data) {
$scope.users2 = data;
});
Factory:
factory.getUser = function(callback) {
$http.get("/user").success(function(output) {
users2 = output;
callback(users2);
});
};
I am trying to pass the hidden values of users2.id and users2.name from the controller/factory into a form. I tried ng-init, ng-value as well as input type="hidden", but none works.
So this is what I did to get it working:
View:
<form>
<textarea ng-model='new_comment.comment' name="comment" rows="4" cols="50">
</textarea>
<br>
<input type="submit" value="Post Comment!" ng-click="addComment(x._id, new_comment, users2.name, users2._id)">
</form>
Controller:
$scope.addComment = function(id, comment, userName, userId) {
var commentValue = comment.comment;
var newComment = {comment: commentValue, name: userName, userId: userId};
postFactory.addComment(id, newComment, function () {
postFactory.getComment(function (data) {
$scope.comments = data;
});
$scope.new_comment = {};
});
};
Try this
<input type="hidden" ng-model='new_comment.userId' value="{{users2.id}}" name="userId" >
And while you are changing things
UserFactory.getUser
.then(function (data) {
$scope.users2 = data;
});
with
factory.getUser = function() {
return $http.get("/user");
};
as $http returns a promise
Two way binding wouldn't work with hidden element, so I'd use ng-value to set the value of type="hidden" element
<input type="hidden" ng-value='new_comment.userId' name="userId"/>
<input type="hidden" ng-value='new_comment.name' name="userName"/>
Do something like this, return the promise.
factory.getUser = function(callback) {
return $http.get("/user")
};
Controller:
UserFactory.getUser().success(function(output) {
$scope.users2 = output.data;
});

Resources