Angularjs dynamically select options on page load - angularjs

I have this app that users can select a list of faults from drop downs drilling down three levels, the issue I am having is when they are opening the item to edit, the first drop down populates on page load and has the selected item from the saved data, the second populates the options but does not select the any items, and the third the same.
controller:
.controller("Ctrl", function ($scope, $http) {
var urlString = systems.systems + "/getIssueCodes/" + Id.Id;
$http({
method: 'GET',
url: urlString,
dataType: "json"
}).then(function successCallback(response) {
var data = response;
if (data.data.name1 !== "") {
$scope.Fault = data.data.name1;
f1 = data.data.id1;
$scope.faultChangedLoad(f1, (data.data.id2 === null ? "" : data.data.id2));
$scope.Fault1 = data.data.name2;
}
if (data.data.name2 !== "") {
f2 = data.data.id2;
$scope.fault1ChangedLoad(f2, (data.data.name3 === null ? "" : data.data.name3));
}
if (data.data.name3 !== null) {
f3 = data.data.id3;
}
$scope.Desc = data.data.desc;
});
$scope.faultChangedLoad = function (Fault, selected) {
var urlStr = systems.systems + "/faultCodes/" + Fault;
$http({
method: 'GET',
url: urlStr,
dataType: "json"
}).then(function successCallback(response) {
$scope.fault1Codes = [];
if (response.data.length > 0) {
var ms4 = angular.element(document.querySelector('#Main-select4'));
ms4.removeClass("no-show");
ms4.addClass("item item-select");
var ms6 = angular.element(document.querySelector('#Main-select6'));
if (ms6.hasClass("item")) {
ms6.removeClass("item item-select");
ms6.addClass("no-show");
}
}
else {
var ms41 = angular.element(document.querySelector('#Main-select4'));
if (ms41.hasClass("item")) {
ms41.removeClass("item item-select");
ms41.addClass("no-show");
}
var ms61 = angular.element(document.querySelector('#Main-select6'));
if (ms61.hasClass("item")) {
ms61.removeClass("item item-select");
ms61.addClass("no-show");
}
}
$scope.fault1Codes = response.data;
$scope.Fault1 = selected;
});
}
$scope.fault1ChangedLoad = function (Fault, selected) {
$http({
method: 'GET',
url: systems.systems + "/faultCodes/" + Fault,
dataType: "json"
}).then(function successCallback(response) {
$scope.fault2Codes = [];
if (response.data.length > 0) {
var ms6 = angular.element(document.querySelector('#Main-select6'));
ms6.removeClass("no-show");
ms6.addClass("item item-select");
}
else {
var ms61 = angular.element(document.querySelector('#Main-select6'));
if (ms61.hasClass("item")) {
ms61.removeClass("item item-select");
ms61.addClass("no-show");
}
}
$scope.fault2Codes = response.data;
$scope.Fault2 = selected;
});
}
}
View:
<label class="item item-select" id="Main-select5">
<span class="input-label">Issue Code:</span>
<select ng-model="Fault" ng-change="faultChanged(Fault)">
<option ng-repeat="faultCode in faultCodes" ng-selected="faultCode.text === Fault" value="{{faultCode.value}}">{{faultCode.text}}</option>
</select>
</label>
<label class="no-show" id="Main-select4">
<span class="input-label"></span>
<select ng-model="Fault1" ng-change="fault1Changed(Fault1)">
<option ng-repeat="fault1Code in fault1Codes" ng-selected="fault1Code.text === Fault1" value="{{fault1Code.value}}">{{fault1Code.text}}</option>
</select>
</label>
<label class="no-show" id="Main-select6">
<span class="input-label"></span>
<select ng-model="Fault2">
<option ng-repeat="fault2Code in fault2Codes" ng-selected="fault2Code.text === Fault2" value="{{fault2Code.value}}">{{fault2Code.text}}</option>
</select>
</label>
<label class="item item-input" id="Main-textarea1">
<span class="input-label">Description:</span><input type="text" placeholder="Enter Description" ng-model="Desc">
</label>
I have looked everywhere for a solution, I have tried ng-options but that did not help.
Any help is appreciated,
Thank you

I found a working solution and I want to put it here in case someone else has the same issue.
I could not find any help so I went back to the books, after reading several chapters, I saw (not mentioned in requirements) a bit of code that displayed ng-value instead of value and I tried it, it worked and the data is being displayed.
Thank you

Related

Dynamic no of drop down list generate as per value in previous drop down list in AngularJS 1.x

I have the following requirement: I have one drop-down list containing Employee records and which is getting filled on page load (JSON format). In that data list I have one value as Approval Level which is an integer value.
Now I want that when I select employee ,as per his Approval Level value I want that no of drop down list get filled with employee data.
Means when I select employee whose Approval Level is 5, I want 5 drop down list below that get filled with Employee records
HTML:-
<div class="col-md-6">
<select class="form-control crl dropdown" placeholder="Approval Level" name="ApprovalLevel" id="ApprovalLevelDDL" required ng-model="insert.Approval_Level" ng-change="makeArray()">
<option value="">Employee Name</option>
<option value="{{list.Approval_Level}}" ng-repeat="list in EmpList">{{list.Emp_Name}}</option>
</select>
<span style="color:red" class="error" ng-show="myForm.DesignationName.$error.required || myForm.DesignationName.touched.required">
Require
</span>
</div>
</div>
<div class="row col-md-10 col-md-offset-1 mypadd" ng-repeat="o in arr">
<div class="col-md-6">
<label for="DepartmentHead">Approval Head</label>
</div>
<div class="col-md-6">
<select class="form-control crl dropdown" placeholder="Approval Level" name="ApprovalLevel_{{$index}}" id="ApprovalLevelDDL_{{$index}}" required ng-model="selectedItem" ng-change="HeadEmployeeList({{$index}})" ng-options="list.Emp_ID as list.Emp_Name for list in ddlArr">
</select>
</div>
</div>
Angular Controller:-
function EmployeeList() {
$http({
method: "POST",
url: "/Employee/GetEmployeeList/",
datatype: "json",
headers: { "ContentType": "application/json" },
}).then(function (data) {
$scope.EmpList = data.data.EmpList;
$rootScope.DataList = data.data.EmpList;
$scope.edatalist = data.data.EmpList;
console.log($rootScope.DataList);
}).catch(function (data) {
$scope.error = data.data;
console.log($scope.error);
});
};
EmployeeList();
$scope.EmployeeDataList = function () {
$http({
method: "POST",
url: "/Employee/GetEmployeeList/",
datatype: "json",
headers: { "ContentType": "application/json" },
}).then(function (data) {
//$rootScope.DataList = data.data.EmpList;
$scope.edatalist = data.data.EmpList;
console.log($scope.edatalist);
}).catch(function (data) {
$scope.error = data.data;
console.log($scope.error);
});
};
$scope.insert = $rootScope.DataList;
$scope.arr = [];
$scope.newardata = [];
$scope.ddlArr = [];
$scope.makeArray = function () {
console.log($scope.insert);
$scope.arr.length = 0;
$scope.EmpList.Emp_ID = parseInt($scope.EmpList.Emp_ID, 10);
$scope.EmployeeDataList();
for (var i = 0; i <= parseInt($scope.insert.Approval_Level) ; i++) {
$scope.arr.push(i);
$scope.EmpList[i].Emp_ID = parseInt($scope.EmpList[i].Emp_ID, 10);
$scope.ddlArr.push($scope.EmpList[i]);
}
$scope.newardata = $scope.arr;
console.log($scope.arr);
console.log($scope.ddlArr);
}
console.log($scope.newardata);
var Emplist = [];
var EDATA = [];
$scope.HeadEmployeeList = function (id) {
console.log($scope.newardata);
var eid = {};
console.log(Emplist);
var data = parseInt(this.EmpList.Emp_ID);
console.log(data);
var index = Emplist.indexOf(parseInt(this.insert.Emp_ID));
var subindex = EDATA.indexOf(parseInt($scope.EmpList.Emp_ID,10));
console.log(index);
console.log(subindex);
if (index < 0){
Emplist.push(this.insert.Emp_ID);
EDATA.push($scope.EmpList.Emp_ID,10);
}
console.log(Emplist.indexOf(this.insert.Emp_ID));
console.log(Emplist);
console.log(EDATA.indexOf(parseInt($scope.EmpList.Emp_ID,10)));
console.log(EDATA);
$scope.EDATA = EDATA;
};

Select option passing null to database

I have a view as below:
<select ng-model="d" ng-options="k.id as k.name for k in act"></select>
<input type="submit" value="Create" ng-click="CreateOpen(Emp)" class="btn btn-default" />
</div>
My Js is as below:
app.factory('crudServiceUser', function ($http) {
crudUserObj = {};
crudUserObj.Create = function (openact) {
var Emp;
Emp = $http({
method: 'Post',
url: '/Employee/BankAccount/Index',
data: openact
}
).then(function (response) {
return response.data;
});
return Emp;
}
return crudUserObj;
});
app.controller('usersController', function ($scope, crudServiceUser) {
$scope.CreateOpen = function (openact) {
crudServiceUser.Create(openact).then(function (result) {
$scope.Msg = alert(result.EName + " Has Been Created Successfully");
})
}
Here is my action method:
public ActionResult Index(tblOpenAct tblopact)
{
if (ModelState.IsValid)
{
objemp.OpenActBs.Insert(tblopact);
return RedirectToAction("Index");
}
return View(tblopact);
}
But the select option is inserting null to database but if I use textbox then it inserts data.
Try like bellow
<select ng-model="d" >
<option ng-repeat="k in act" value="{{k.id}}">{{k.name }} </option>
</select>

AngularJS calling a rest service with parameter raises syntax error

I have a .net web service containg two methods getUserTasks & getAllTasks(noOfDays) both return valid Json Data. Have verified it with JSONLINT.
var app = angular.module('tasksApp', []);
app.controller('taskController', function($scope, $http, taskGroupFactory) {
$scope.LoadTasks = function(taskFilter, dateFilter) {
console.log(taskFilter + '-' + dateFilter);
if (taskFilter == 'Self') {
$scope.enableFilters = true;
//$scope.taskGroups = taskGroupFactory.getUserTasks();
var getUTasks = taskGroupFactory.getUserTasks();
getUTasks.then(
function(tasks) {
console.log("success");
$scope.taskGroups = tasks.data;
}, function(errorData) {
console.log("Error: " + errorData);
});
};
if (taskFilter == 'All') {
$scope.enableFilters = false;
var getAllTasks = taskGroupFactory.getAllUserTasks(dateFilter);
getAllTasks.then(
function(tasks) {
console.log("success");
$scope.taskGroups = tasks.data;
}, function(errorData) {
console.log("Error: " + errorData);
});
//$scope.taskGroups = taskGroupFactory.getAllUserTasks(dateFilter);
// $scope.taskGroups = taskGroupFactory.getAllUserTasks(dateFilter)
// .success(function (tasks) {
// console.log('success');
// $scope.taskGroups = tasks.data;
// })
// .error(function (error) {
// console.log(error);
// });
};
};
});
app.factory('taskGroupFactory', function($http) {
var factory = {};
var serviceUrl = '/_layouts/SP.TaskDashboard/WebService/TaskService.asmx';
factory.getUserTasks = function() {
//return $http.post(serviceUrl + '/GetMyTasks');
return $http({
method: 'post',
url: serviceUrl + '/GetMyTasks',
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
});
};
factory.getAllUserTasks = function(taskDateFilter) {
//var serviceUrl = '/_layouts/SP.TaskDashboard/WebService/TaskService.asmx';
// return $http.post(serviceUrl + '/GetAllTasks', { dateFilter: taskDateFilter })
// .success(function (tasks) {
// return tasks;
// })
// .error(function(errorData) {
// return errorData;
// });
// return $http({
// method: 'post',
// url: serviceUrl + '/GetAllTasks',
// headers: { "Content-Type": "application/json", "Accept": "application/json" }
// });
return $http.post(serviceUrl + '/GetAllTasks', {
dateFilter: taskDateFilter
});
//[{"WebTitle": "Press Releases","WorkflowName": "","Tasks": [{"ID": 1,"Title": "Test","WebTitle": "Press Releases","Status": "Not Started","EncodedAbsoluteUrl": "http://sukcw-vwi-sps02:2010/","ItemLink": "PressReleases/WorkflowTasks/1_.000","WorkflowLink": "","WorkflowName": "","ListId": "9F8054AD-E8C4-47B7-B9DB-24FA05853F31","DueDate": "/Date(1422316800000)/","Created": "/Date(1421327050000)/","ParentItemTitle": "","Classification": "overdue"},{"ID": 2,"Title": "Another Test","WebTitle": "Press Releases","Status": "Not Started","EncodedAbsoluteUrl": "http://sukcw-vwi-sps02:2010/","ItemLink": "PressReleases/WorkflowTasks/2_.000","WorkflowLink": "","WorkflowName": "","ListId": "9F8054AD-E8C4-47B7-B9DB-24FA05853F31","DueDate": "/Date(1422057600000)/","Created": "/Date(1421746613000)/","ParentItemTitle": "","Classification": "overdue"}]}, {"WebTitle": "Test","WorkflowName": "test apprvl workflow","Tasks": [{"ID": 29,"Title": "Please approve 05live-ego","WebTitle": "Test","Status": "Not Started","EncodedAbsoluteUrl": "http://sukcw-vwi-sps02:2010/","ItemLink": "sites/responsive/test/WorkflowTasks/29_.000","WorkflowLink": "http://sukcw-vwi-sps02:2010/sites/responsive/test/Documents/05live-ego.jpg","WorkflowName": "test apprvl workflow","ListId": "6A288BE5-51DD-43BE-B036-4B4A73BFAA5C","DueDate": null,"Created": "/Date(1426854267000)/","ParentItemTitle": " 05live-ego","Classification": "upcoming"}]}]
};
return factory;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="tasksApp">
<div ng-controller="taskController">
<button type="button" class="btn btn-info" ng-click="toggle()">Show Pending Tasks</button>
<div ng-hide="myVar">
<input type="radio" name="taskType" value="Self" ng-model="taskFilter" ng-change="LoadTasks(taskFilter, null)" />My Tasks
<input type="radio" name="taskType" value="All" ng-model="taskFilter" ng-change="LoadTasks(taskFilter,list_day_option)" />All Tasks
<span ng-hide="enableFilters"> show tasks created in last <select ng-options="o.id as o.name for o in list_day_options.data" ng-model="list_day_option" ng-change="LoadTasks(taskFilter,list_day_option)"></select></span>
<div class="btn-group legendWrapper" ng-init="classificationFilter='duetoday'">
Overdue
Due today
Upcoming
Show all
</div>
<div class="panel-group">
<div ng-repeat="t in taskGroups" ng-click="itemClicked($index)" class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">{{t.WebTitle + '-' + '(' + filtered.length + ')'}}</h4>
</div>
<div ng-class="applyToggleClass($index)">
<div ng-repeat="tsk in t.Tasks | filter:t.Classification=getClassificationFilter() as filtered" ng-class="applyTskClass(tsk)">
<span>{{tsk.Title}} </span><span ng-class="applyStatusStyle(tsk)">{{tsk.Status}}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Method call to getUserTasks from factory works fine, where as method call to getAllUserTasks(dateFilter) raises syntax error. No error in fiddler, shows the valid json data!! with status 200 but when I debug the script control goes into error block doesnot reach success block :( I have different ways to invoke the service method with parameter but nothing works. As you can see in the comments, feel it is to do with the way I am calling the webservice or passing the parameter to $http.post, please help.
Thanks

AngularJS orderBy not working with trackBy

I don't know why orderBy is not working with trackBy, it is making me crazy :(
Here is my HTML code:
<div class="blocks-container" ng-init="loadProjects()" ng-controller="buildMonitorController">
<div class="row">
<!-- <div> -->
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-2 block animate"
ng-if="!errorDialogActive"
ng-repeat="build in builds.builds.build track by build._id | orderBy:'lastBuildDetails.startDate' : true"
ng-class="{'running': project.running ,'block-green': build._status ==='SUCCESS','block-red': build._status==='FAILURE'}"
id="{{build._id}}">
<div class="title-container"><p>{{build._buildTypeId}}</p></div>
<div class="update-container col-xs-12">
<time>{{ build.lastBuildDetails.startDate | date : 'dd.MM.yyyy H:mm:s'}}</time>
</div>
</div>
</div>
<!--</div>-->
<!-- Start error state dialog -->
<div ng-include src="'views/main/error-dialog.html'"></div>
Everytime give me the same result even if i change the order to reverse
And Here my AngularJS code:
$scope.refreshBuilds = function () {
$scope.errorList.length = 0
//#TODO remove this part right after the API is working
//Init
var suffix = '';
var randomnumber = Math.floor(Math.random() * 3);
//simulate mock by random number
switch (randomnumber) {
case 1:
suffix = '-success';
break;
case 2:
suffix = '-less';
break;
default:
break;
}
var url = 'mock/builds'+suffix+'.xml';
console.log('url: ' + url)
$http({
method: 'GET',
url: url,
headers: {
Authorization: 'Basic AAA'
}
}).success(function (data, status) {
//Recive builds from xml and reset scope
var buildsToFilter = new X2JS().xml_str2json(data);
$scope.errorDialogActive = false;
//filter builds which have a no build API detail status
if (buildsToFilter.builds.build !== undefined) {
angular.forEach(buildsToFilter.builds.build, function (build, index) {
$http({
method: 'GET',
url: 'mock/build-'+build._id+'.xml',
headers: {
Authorization: 'Basic AAA'
}
}).success(function (buildDetailData) {
$scope.errorDialogActive = false;
//push detail data into build array
buildsToFilter.builds.build[index].lastBuildDetails = new X2JS().xml_str2json(buildDetailData).build;
console.log(buildsToFilter.builds.build[index]);
}).error(function (data, status) {
$scope.errorDialogActive = true;
//remove build from index if no build detail was found
buildsToFilter.builds.build.splice(index, 1);
$scope.setError(status, '', '');
}).then(function () {
//after filtering builds to display, setup builds $scope for FrontEnd
$scope.builds = buildsToFilter;
});
});
} else {
}
}).error(function (data, status) {
//active dialog if error happens & set error
$scope.errorDialogActive = true;
$scope.setError(status, 'builds', '');
}).then(function () {
$timeout(function () {
$scope.finishedRequest = true;
}, 5000);
//refresh right after proceed and a little delay
$timeout(function () {
console.log('Starting refresh');
$scope.refreshBuilds();
}, 21000);
})
};
If You need more code please let me know
Try reading the docs. It doesn't appear you are using it correctly.
https://docs.angularjs.org/api/ng/filter/orderBy
The last argument can only be "reverse".
Move 'track by build._id' to the end of the expression (after orderBy).
ng-repeat="build in builds.builds.build track by build._id | orderBy:'lastBuildDetails.startDate'

Angularjs ng-repeat radio button list: selected radio returning undefined value

I have found a lot of people with the same question but the answers given don't work for me.
This is my code:
<div ng-controller="addEventController">
//other form input fields that will be sent when clicking the button
<div ng-controller="imgListCtrl">
<input ng-repeat-start="image in images" name = "selectImage" type="radio" ng-
model="img" ng-value="{{image.imageid}}"/>
<img class="images" ng-src="{{image.url}}" width="50" height="50"/>
<br ng-if="($index+1) % 10 == 0"/><br ng-if="($index+1) % 10 == 0"/>
<span ng-repeat-end></span>
</div>
<button class="btn-default" ng-click="saveEvent()">Opslaan</button>
</div>
this is a child controller of 'addEventController' and in the parent controller I try to acces the selected radio button value like this:
myAppProfile.controller('addEventController', function($scope,$location, $http) {
$scope.saveEvent = function() {
$http({
method: 'POST',
url: 'eventController.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
'begin': $scope.begin + " " + $scope.btijd,
'einde': $scope.einde + " " + $scope.etijd,
'beschrijving': $scope.beschrijving,
'img': $scope.img
}
}).
success(function(data, status) {
if(data == "1"){
$location.path("/agenda");
}else{
$scope.errormsg = data;
}
}).
error(function(data, status) {
$scope.errormsg = data;
});
}
});
$scope.img => always returns "undefined".
I have found that you have to rename the ng-model object to $parent.img or that you have to name it images.img, I have tried all the answers I found online, but in my case, always undefined. Anyone have an idea of how I could get the value of the selected radiobutton?
Found the answer right after posting, maybe it can help someone. It wasn't enough to do $parent.img because that only goes to the scope of the child controller, but i had to do: ng-model="$parent.$parent.img" to go up to the parent controller..
Why not defined a scope property on addEventController and hoist the child scope properties?
<div ng-controller="addEventController">
//other form input fields that will be sent when clicking the button
<div ng-controller="imgListCtrl">
<input ng-repeat-start="image in images" name = "selectImage" type="radio" ng-
model="event.img" ng-value="{{image.imageid}}"/>
<img class="images" ng-src="{{image.url}}" width="50" height="50"/>
<br ng-if="($index+1) % 10 == 0"/><br ng-if="($index+1) % 10 == 0"/>
<span ng-repeat-end></span>
</div>
<button class="btn-default" ng-click="saveEvent()">Opslaan</button>
</div>
myAppProfile.controller('addEventController', function($scope,$location, $http) {
$scope.event = {};
$scope.saveEvent = function() {
$http({
method: 'POST',
url: 'eventController.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
'begin': $scope.event.begin + " " + $scope.event.btijd,
'einde': $scope.event.einde + " " + $scope.event.etijd,
'beschrijving': $scope.event.beschrijving,
'img': $scope.event.img
}
}).
success(function(data, status) {
if(data == "1"){
$location.path("/agenda");
}else{
$scope.errormsg = data;
}
}).
error(function(data, status) {
$scope.errormsg = data;
});
}
});

Resources