Editing an item from ng-repeat - html

So far I've been successful in creating a function that removes an element from ng-repeat and to toggle a form. I can't figure out how to edit a given element in that ng-repeat.
Ideally, I'd like to click on the element, and have the form show with the existing values already in the input. So that all the user needs to do is edit whichever fields desired, click submit and that newly updated item is then added back to the array where it originally was.
This is what I've come up with:
<div ng-app="testApp">
<div ng-controller="testCtrl as vm">
<form ng-show="vm.showEditForm">
<input type="text" />
<input type="text" />
<button ng-click="vm.update()">Submit</button>
</form>
<table>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<tr ng-repeat="item in vm.list">
<td>
{{item.name}}
</td>
<td>
{{item.desc}}
<span ng-click="vm.toggleEditForm()">E</span>
<span ng-click="vm.removeItem($index)">X</span>
</td>
</tr>
</table>
</div>
</div>
and:
angular
.module('testApp', [])
.controller('testCtrl', testCtrl)
.service('testSrvc', testSrvc);
function testCtrl(testSrvc) {
var vm = this;
vm.list = testSrvc.list;
vm.removeItem = function(idx) {
testSrvc.remove(idx);
}
vm.showEditForm = false;
vm.toggleEditForm = function() {
vm.showEditForm = !vm.showEditForm;
};
vm.update = function() {
// ???
}
}
function testSrvc() {
this.list = [
{
name: 'asdf',
desc: 'lorem ipsum dolor'
},
{
name: 'qwerty',
desc: 'lorem ipsum amet'
}
];
this.remove = function(itemIndex) {
this.list.splice(itemIndex, 1);
};
this.edit = function() {
this.list.splice() //???
}
}

You need to tell which item you want to edit. So it should be
<span ng-click="vm.edit(item)">E</span>
Then this function should store a copy of that item to edit in some variable:
vm.edit= function(item) {
vm.editedItem = angular.copy(item);
};
And the form should be bound to this item copy:
<input type="text" ng-model="vm.editedItem.name"/>
<input type="text" ng-model="vm.editedItem.desc"/>
Then the save method should find back the original item in the array (thanks to its ID or index), and copy the edited fields from vm.editedItem.

angular
.module('testApp', [])
.controller('testCtrl', testCtrl)
.service('testSrvc', testSrvc);
function testCtrl(testSrvc) {
var vm = this;
vm.list = testSrvc.list;
this.index1 = -1;
vm.removeItem = function(idx) {
testSrvc.remove(idx);
}
vm.showEditForm = false;
vm.toggleEditForm = function(item,index) {
this.show = true;
this.index1 = index;
};
vm.update = function(item,index) {
vm.list[index].name = item.name;
vm.list[index].desc = item.desc;
this.index1 = -1;
}
}
function testSrvc() {
this.show = false;
this.list = [
{
name: 'asdf',
desc: 'lorem ipsum dolor'
},
{
name: 'qwerty',
desc: 'lorem ipsum amet'
}
];
this.remove = function(itemIndex) {
this.list.splice(itemIndex, 1);
};
this.edit = function(index) {
this.show = true;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp">
<div ng-controller="testCtrl as vm">
<form ng-show="vm.showEditForm">
</form>
<table>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<tr ng-repeat="item in vm.list" >
<td>
{{item.name}}
</td>
<td>
{{item.desc}}
<span ng-click="vm.toggleEditForm(item,$index)">E</span>
<input ng-show="vm.index1 == $index" type="text" ng-model="item.name" />
<input ng-show="vm.index1 == $index" type="text" ng-model="item.desc" />
<button ng-show="vm.index1 == $index" ng-click="vm.update(item,$index)">Submit</button>
<span ng-click="vm.removeItem($index)">X</span>
</td>
</tr>
</table>
</div>
</div>

Related

How to keep state of the checkbox after the reload the page in angular 9?

I am trying to check the multiple checkboxes, when the page reloads, the state is restored to default (unchecked) and I've been buzzing my head with this. by the way I stored the checked value in the local storage but I do not know how to map it to the HTML checkbox for checked when the page reloads. please help me.
.html
<tbody>
<tr *ngFor="let p of pmDetails1">
<td>
<input type="checkbox" name="{{p.id}}" [value]="p.id" (change)="getEmployeeId($event,p.id)">
</td>
<td>
{{p.firstName}} {{p.lastName}}
</td>
<td>
{{p.jobTitle.jobTitleName}}
</td>
</tr>
</tbody>
.ts
ngOnInit() {
this.userService.getAllUsers().subscribe((x: IEmployee[]) => {
this.pmDetails1 = x;
});
this.selectedItem = new Array<number>();
this.selectedEmployee = new Array<number>();
console.log("localStorage", localStorage.getItem("selected"));
this.selectedItem = JSON.parse(localStorage.getItem("selected"));
}
//onSaveEmployee is a function for the button to the confirm that I checked,
onSaveEmployee() {
localStorage.setItem("selected",JSON.stringify(this.selectedEmployee));
}
getEmployeeId(e:any,id:string){
if(e.target.checked){
this.selectedEmployee .push(id);
}
else{
this.selectedEmployee = this.selectedEmployee.filter(m => m!=id);
}
}
IEmployee interface
export interface IEmployee {
id: number;
firstName: string;
jobTitle: any;
lastName: String;
}
Finaly I found a way to do it. its like this.
.html
<tbody>
<tr *ngFor="let p of pmDetails1">
<td>
<input type="checkbox" name="{{p.id}}" [value]="p.id (change)="getEmployeeId($event,p.id)" [checked]="isChecked(p.id)"/>
</td>
<td>
{{p.firstName}} {{p.lastName}}
</td>
<td>
{{p.jobTitle.jobTitleName}}
</td>
</tr>
</tbody>
.ts
ngOnInit() {
this.userService.getAllUsers().subscribe((x: IEmployee[]) => {
this.pmDetails1 = x;
});
if(localStorage.getItem("selected")){
this.selectedEmployee = JSON.parse(localStorage.getItem("selected"));
}
}
// to save checked value
onSaveEmployee() {
localStorage.setItem("selected",JSON.stringify(this.selectedEmployee));
this.dialogRef.close(this.selectedEmployee);
this.selectedEmployee = [];
}
getEmployeeId(e:any,id:string){
if(e.target.checked){
this.selectedEmployee .push(id);
}
else{
this.selectedEmployee = this.selectedEmployee.filter(m => m!=id);
}
}
isChecked(id:number){
for (let index = 0; index < this.selectedEmployee.length; index++) {
if(id == this.selectedEmployee[index]){
return true;
}
}
return false;
}

How to make a table row editable to update the value in Angular?

I'm trying to build an Angular application that takes data from an excel sheet and displays it in a table on upload. I have added an edit link under one column for editing the row data, upon clicking edit it shows save and cancel buttons. I tried to implement this functionality with some components but it didn't work out as I expected.
Can someone suggest to me a way to implement this, please?
-> app.component.html
<div>
<h3>Upload Excel File</h3>
<div class="row">
<input type="file" (change)="uploadFile($event)" placeholder="Choose File" accept=".xls,.xlsx,.ods">
<button type="button" class="btn btn-info" (click)="upload()" >Upload</button>
</div>
</div>
<br>
<div>
<table *ngIf="submitted">
<tr>
<th *ngFor = "let column of tableHeaders">
{{column}}
</th>
</tr>
<tr *ngFor = "let row of excelData; let i=index">
<td >
{{row["Employee Name"]}}
</td>
<td>
{{row["Email Id"]}}
</td>
<td>
{{row["UID"]}}
</td>
<td>
{{row["place"]}}
</td>
<td>
{{row["DOB"]}}
</td>
<td>
<button *ngIf="enableEdit && enableEditIndex == i" (click)="enableEdit=false" class="btn page-secondary-action-btn" ng-click="cancel()">Cancel</button>
<button *ngIf="enableEdit && enableEditIndex == i" id="saveBtn" class="btn page-primary-action-btn" (click)="saveSegment()" type="submit">Save</button>
Edit
</td>
</tr>
<tr>
</tr>
</table>
</div>
-> app.component.ts
import { Component } from '#angular/core';
import * as XLSX from 'xlsx';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'excelUpload';
buffer: any;
file: File;
worksheet: any;
excelData: any[];
excelDatas: any[];
tableData: any[];
uploadFile(event) {
this.file = event.target.files[0];
}
private dataLoaded: boolean;
submitted: boolean = false;
tableHeaders = ["Employee Name", "Email Id", "place", "UID", "DOB", "Actions"];
tableRows = [];
enableEdit: boolean = false;
enableEditIndex = null;
upload() {
this.submitted = true;
let fileReader = new FileReader();
fileReader.onload = (e) => {
this.buffer = fileReader.result;
var data = new Uint8Array(this.buffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) {
arr[i] = String.fromCharCode(data[i]);
}
var bstr = arr.join("");
var workbook = XLSX.read(bstr, { type: "binary" });
var first_sheet_name = workbook.SheetNames[0];
var worksheet = workbook.Sheets[first_sheet_name]; // worksheet_name
this.excelData = XLSX.utils.sheet_to_json(worksheet, { raw: true })
this.excelDatas = this.excelData.map(data => Object.values(data));
console.log(this.excelData);
// console.log(this.excelData[0]["Email Id"]);
// var newArr = this.excelData.map((data, index) => {
// console.log(data)
// })
}
fileReader.readAsArrayBuffer(this.file);
}
editRowData(e, i) {
this.enableEdit = true;
this.enableEditIndex = i;
}
saveSegment(){}
}
I was able to fix my issue with NG-ZORRO components. NG-ZORRO table components have an Editable Cells component with which I was able to edit each row inside the tables.
Reference:
Click here for reference
=> app.component.ts
import { Component } from '#angular/core';
import * as XLSX from 'xlsx';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'edit-table';
i = 0;
editId: string | null = null;
listOfData: any;
file: File;
buffer: any;
worksheet: any;
excelData: any[];
tableData: any;
uploadFile(event) {
this.file = event.target.files[0];
}
submitted: boolean = false;
// function to read data from excel
upload() {
this.submitted = true;
let fileReader = new FileReader();
fileReader.onload = (e) => {
this.buffer = fileReader.result;
var data = new Uint8Array(this.buffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) {
arr[i] = String.fromCharCode(data[i]);
}
var bstr = arr.join("");
var workbook = XLSX.read(bstr, { type: "binary" });
var first_sheet_name = workbook.SheetNames[0];
var worksheet = workbook.Sheets[first_sheet_name]; // worksheet_name
this.excelData = XLSX.utils.sheet_to_json(worksheet, { raw: true })
// this.tableData = this.excelData.map(data => Object.values(data));
}
fileReader.readAsArrayBuffer(this.file);
}
startEdit(id: string): void {
this.editId = id;
}
stopEdit(): void {
this.editId = null;
}
addRow(): void {
this.tableData = [
];
this.i++;
}
deleteRow(id: string): void {
this.tableData = this.tableData.filter(d => d.id !== id);
}
}
=> app.component.html
<div>
<h3>Upload Excel File</h3>
<div class="row">
<input type="file" (change)="uploadFile($event)" placeholder="Choose File" accept=".xls,.xlsx,.ods">
<button type="button" class="btn btn-info" (click)="upload()" >Upload</button>
</div>
</div>
<br />
<br />
<nz-table #editRowTable nzBordered [nzData]="excelData" *ngIf="submitted">
<thead>
<tr>
<th>Employee Name</th>
<th>Email Id</th>
<th>UID</th>
<th>place</th>
<th>DOB</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let data of editRowTable.data" class="editable-row">
<td>
<div class="editable-cell" [hidden]="editId === data.id" (click)="startEdit(data.id)">
{{ data['Employee Name'] }}
</div>
<input [hidden]="editId !== data.id" type="text" nz-input [(ngModel)]="data['Employee Name']" (blur)="stopEdit()" />
</td>
<td>
<div class="editable-cell" [hidden]="editId === data.id" (click)="startEdit(data.id)">
{{ data['Email Id']}}
</div>
<input [hidden]="editId !== data.id" type="text" nz-input [(ngModel)]="data['Email Id']" (blur)="stopEdit()" />
</td>
<td>
<div class="editable-cell" [hidden]="editId === data.id" (click)="startEdit(data.id)">
{{ data['UID']}}
</div>
<input [hidden]="editId !== data.id" type="text" nz-input [(ngModel)]="data['UID']" (blur)="stopEdit()" />
</td>
<td>
<div class="editable-cell" [hidden]="editId === data.id" (click)="startEdit(data.id)">
{{ data['Place'] }}
</div>
<input [hidden]="editId !== data.id" type="text" nz-input [(ngModel)]="data['Place']" (blur)="stopEdit()" />
</td>
<td>
<div class="editable-cell" [hidden]="editId === data.id" (click)="startEdit(data.id)">
{{ data['DOB'] }}
</div>
<input [hidden]="editId !== data.id" type="text" nz-input [(ngModel)]="data['DOB']" (blur)="stopEdit()" />
</td>
</tr>
</tbody>
</nz-table>

How to push list of objects to model using ng-model and ng-repeat AngularJS

I have to call a POST function, and need to compress the data in web form into an object in advance. I use ng-repeat to display all data input, and init this value for input, but I have no idea how to use ng-model to save the data.
I can resolve this case by setting an dynamic id for input, and using JQuery to get data, but it's not a good solution. And I want use AngularJS model only.
Please give me an advice. Below is my code:
Click here to see the screenshot of UI form
html file
<!-- edit-user-page-view -->
<div spectrum-error-container
data-scope-id="$id"
class="col-sm-12"></div>
<div class="email-preference-block">
<form name="editUserForm"
id="editUserForm"
role="form"
class="prj-form prj-create-user-form">
<fieldset id="fieldsetAccountInformation">
<legend>{{ 'user.userPage.form.fieldsets.accountInformation' | translate }}</legend>
<div class="row language-preference-block">
<div class="form-group">
<div class="col-md-12 col-sm-12">
<label data-translate="user.userPage.form.preferredLanguage"></label>
</div>
<div class="col-md-12 col-sm-12">
<label data-ng-repeat="option in preferencesData.languageOptionList"
class="radio-inline">
<input type="radio"
ng-model="emailNotificationModel.selectedLanguageValue"
value="{{ option.value }}"> {{ option.label | translate }}
</label>
</div>
</div>
</div>
<div class="row user-preference-block">
<table data-ng-repeat="preferenceItem in preferencesData.userNotificationPreferencesList"
class="table table-bordered table-striped user-preference-table">
<thead>
<tr>
<th>{{ preferenceItem.label | translate }}</th>
<th>{{ 'organisation.mediaPreference.selected' | translate }}?</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="mediaOption in preferenceItem.mediaOptionList">
<td class="first-column">
{{ mediaOption.label | translate}}
</td>
<td class="second-column">
<input type="checkbox"
id="inputStatus1-{{ mediaOption.id }}"
value="{{ mediaOption.id }}"
ng-checked="mediaOption.userChoice"
data-ng-click="clickHandler.checkValue(mediaOption.id)">
</td>
</tr>
</tbody>
</table>
</div>
<div class="prj-form-actions"
data-spectrum-style-affix
data-threshold="150"
data-css-class="sdx-sticky-container">
<button id="selectAllButton"
class="btn btn-default"
type="button"
data-ng-click="clickHandler.selectAll()"
data-translate="global.buttons.selectAll">
</button>
<button id="deselectAll"
class="btn btn-default"
type="button"
data-ng-click="clickHandler.deselectAll()"
data-translate="global.buttons.deselectAll">
</button>
<button id="saveBtn"
class="btn btn-default"
type="button"
data-ng-click="clickHandler.saveButton()"
data-translate="global.buttons.save">
</button>
<button id="cancelBtn"
class="btn btn-default"
type="button"
data-ng-click="clickHandler.deselectAll()"
data-translate="global.buttons.cancel">
</button>
</div>
</fieldset>
</form>
</div>
<div class="clearfix"></div>
<!-- / edit-my-account-page-view -->
controller file:
angular.module(
'EditUserPreferencesPageControllerModule',
[]
).controller(
'EditUserPreferencesPageController',
[
'$scope',
'$location',
'$routeParams',
'$filter',
'$window',
'$modal',
'PageTitleModel',
'SpectrumPageHeaderModel',
'AccountModel',
'UserModel',
'OrganisationService',
'RolesModel',
'MediaPreferencesModel',
'UserService',
'EmailNotificationService',
'EmailNotificationModel',
'SpectrumErrorModel',
'SpectrumHATEOASHelper',
function ($scope,
$location,
$routeParams,
$filter,
$window,
$modal,
PageTitleModel,
SpectrumPageHeaderModel,
AccountModel,
UserModel,
OrganisationService,
RolesModel,
MediaPreferencesModel,
UserService,
EmailNotificationService,
EmailNotificationModel,
SpectrumErrorModel) {
var impersonateUserCode = AccountModel.account.impersonatedUserCode,
userCode = impersonateUserCode ? impersonateUserCode : $routeParams.userCode;
$scope.mediaPreferencesModel = MediaPreferencesModel;
$scope.userModel = UserModel;
$scope.emailNotificationModel = EmailNotificationModel;
$scope.rolesModel = RolesModel;
$scope.statusList = [];
$scope.relationshipNotificationList = [];
$scope.auditNotificationList = [];
$scope.testListMediaValue = [];
$scope.preferencesData = {};
$scope.pleaseSelect = $filter('translate')('global.placeholders.pleaseSelect');
function initialise() {
PageTitleModel.setTitle('user.pageTitles.emailNotification');
SpectrumPageHeaderModel.setTitle('user.pageTitles.emailNotification');
SpectrumErrorModel.clearErrorsForScope($scope.$id);
generateOptions();
loadUserData();
}
function generateOptions() {
for (var status in MediaPreferencesModel.STATUS) {
if (MediaPreferencesModel.STATUS[status].domainType === 'Relationship') {
$scope.relationshipNotificationList.push(MediaPreferencesModel.STATUS[status]);
} else if (MediaPreferencesModel.STATUS[status].domainType === 'Audit') {
$scope.auditNotificationList.push(MediaPreferencesModel.STATUS[status]);
}
}
}
function loadUserData() {
UserService.getOne(userCode).then(
function successHandler(successResponse) {
UserModel.populateFromJSON(successResponse.data);
getNotificationPreferences();
},
function errorHandler(errorResponse) {
SpectrumErrorModel.handleErrorResponse($scope.$id, errorResponse);
}
);
}
function getNotificationPreferences() {
EmailNotificationService.getNotificationPreferences(UserModel.userCode).then(
function successHandler(successResponse) {
$scope.preferencesData = successResponse.data;
EmailNotificationModel.populateData($scope.preferencesData);
},
function errorHandler(errorResponse) {
SpectrumErrorModel.handleErrorResponse($scope.$id, errorResponse);
}
);
}
function saveData() {
var a = $scope.testListMediaValue;
EmailNotificationService.saveNotificationPreferences(UserModel.userCode, EmailNotificationModel.getJsonForSavePreferences()).then(
function successHandler(successResponse) {
console.log(successResponse);
},
function errorHandler(errorResponse) {
SpectrumErrorModel.handleErrorResponse($scope.$id, errorResponse);
}
);
}
$scope.clickHandler = {
saveButton: function () {
saveData();
},
backButton: function () {
$location.path(viewUserPath());
},
selectAll: function () {
angular.forEach(MediaPreferencesModel.relationshipStatus, function (itm) {
itm.userChoice = true;
});
},
deselectAll: function () {
angular.forEach(MediaPreferencesModel.relationshipStatus, function (itm) {
itm.userChoice = false;
});
},
checkValue: function (isChecked) {
console.log(isChecked);
}
};
function viewUserPath() {
return '/user/view/' + userCode;
}
$scope.canShow = {
emailPreferences: function () {
var preferenceFields = MediaPreferencesModel.preferenceFields;
return (preferenceFields.length > 0);
},
isRelationshipNotification: function (reference) {
return reference.domainType === 'Relationship';
},
isAuditNotification: function (reference) {
return reference.domainType === 'Audit';
}
};
initialise();
}
]
);
model
angular.module(
'EmailNotificationModelModule',
[]
).factory(
'EmailNotificationModel', [
function () {
return {
selectedLanguageValue: '',
userNotificationPreferencesList: [],
getJsonForSavePreferences: function () {
var json = {};
json.selectedLanguageValue = this.selectedLanguageValue;
json.userNotificationPreferencesList = this.userNotificationPreferencesList;
return json;
},
populateData: function (preferencesData) {
this.selectedLanguageValue = preferencesData.selectedLanguage.value;
}
};
}
]
);
JSON parse when I call get function to generate form
{
selectedLanguage: {
label: 'Spain',
value: 'sp'
},
languageOptionList: [
{
label: 'English',
value: 'en'
},
{
label: 'Chinese',
value: 'cn'
},
{
label: 'Spain',
value: 'sp'
},
{
label: 'French',
value: 'fr'
},
{
label: 'Portuguese',
value: 'po'
},
{
label: 'Japanese',
value: 'jp'
}
],
userNotificationPreferencesList: [
{
label: 'organisation.mediaPreference.tradingRelationships',
domainType: 'tradingRelationShip',
mediaOptionList: [
{
id: 'ACCEPTED',
label: 'organisation.relationshipStatuses.accepted',
order: 1,
userChoice: true
},
{
id: 'INITIATED',
label: 'organisation.relationshipStatuses.initiated',
order: 2,
userChoice: false
},
{
id: 'REJECTED',
label: 'organisation.relationshipStatuses.rejected',
order: 3,
userChoice: true
}
]
},
{
label: 'organisation.mediaPreference.auditNotifications',
domainType: 'auditNotification',
mediaOptionList: [
{
id: 'AUDIT_CREATED',
label: 'organisation.auditStatuses.created',
order: 4,
userChoice: true
},
{
id: 'AUDIT_ACCEPTED',
label: 'organisation.auditStatuses.accepted',
order: 5,
userChoice: false
}
]
}
]
};
The correct way to use NgModel with input[checkbox] can be found here.
For your implementation, change this
<input type="checkbox"
id="inputStatus1-{{ mediaOption.id }}"
value="{{ mediaOption.id }}"
ng-checked="mediaOption.userChoice"
data-ng-click="clickHandler.checkValue(mediaOption.id)">
To this
<input type="checkbox"
ng-model="mediaOption.userChoice"
ng-change="clickHandler.checkValue(mediaOption.id)">

How to select dropdownlist values of particular text value which is in ng-repeat and ng-model in angularjs and how can we post it to database

I'm pretty new to angularjs.So,please kindly ignore if there are any errors.Here I have one dropdownlist within ng-repeat if I select the values in dropdownlist the corresponding Item code and the selected description from dropdownlist should pass to angularcontroller and I need to post it to the mvc controller
angular.module('myApp', [])
.controller('ctrl', ['$scope', '$http', '$rootScope',function ($scope, $http,$rootScope) {
$scope.values = [{
Code: 1,
Description: 'Apple'
}, {
Code: 2,
Description: 'Orange'
}, {
Code: 3,
Description: 'Mango'
}, {
COde: 4,
Description: 'Guva'
}
];
$scope.ddlrhs = '';
$scope.data = [{
Code: 1,
Description: 'Red'
}, {
Code: 2,
Description: 'Orange'
}, {
Code: 3,
Description: 'Yellow'
}, {
Code: 4,
Description: 'Green'
}
];
$scope.submit = function ()
{
$scope.list = [];
for (var i = 0; i < $scope.values.length; i++) {
var j = "";
$scope.list.push({
VALUE: $scope.values[i].Code,
Description: $scope.myForm.items[i].Description
})
}
$http({
method: "POST",
url: "/Controller/Save",
data:
$scope.list
})
}
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<div id="dvcollection" ng-App="myApp" ng-controller="ctrl" >
<form name="myForm" >
<table id="tblcollections">
<thead>
<tr >
<th>ItemCode</th>
<th>ItemDesc</th>
<th>DropdownDesc</th>
<th>DropdownCode</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in values">
<td><span>{{item.Code}}</span> </td>
<td>{{item.Description}}</td>
<td>
<select ng-model="myForm.items[$index]" ng-options=" element.Description for element in data ">
<option value="">Select </option>
</select>
</td>
<td><span>{{myForm.items[$index].Code}}</span></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<input type="button" value="save" ng-click="submit()"style="float:right;" >
</td>
</tr>
</tbody>
</table>
</form>
</div>
Hey May be this might be your expectation
<div ng-app="myApp" >
<div id="dvcollection" ng-controller="ctrl">
<form name="myForm">
<table id="tblcollections">
<thead>
<tr>
<th>ItemCode</th>
<th>ItemDesc</th>
<th>DropdownDesc</th>
<th>DropdownCode</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in values">
<td><span>{{item.Code}}</span> </td>
<td>{{item.Description}}</td>
<td>
<select ng-model="itemssample" ng-options=" element.Description for element in data " ng-change="pushingelement(item.Code,itemssample.Code)">
<option value="">Select </option>
</select>
</td>
<td><span>{{myForm.items[$index].Code}}</span></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<input type="button" value="save" ng-click="submit()" style="float:right;">
</td>
</tr>
</tbody>
</table>
</form>
<div> This is written to ensure that mapping is stored or not. (Not necessary)
<p ng-repeat="item in list">
Mapping of {{$index}} element {{item.ItemCode}} -> {{item.ColorCode}}
</p>
</div>
</div>
</div>
Ensure that your MVC Controller should have a model as
public class MapperClass
{
public int ItemCode { get; set; }
public int ColorCode { get; set; }
}
SCRIPT
angular.module('myApp', [])
.controller('ctrl', ['$scope', '$http', '$rootScope', function ($scope, $http, $rootScope) {
$scope.list = [];
$scope.values = [
{ Code: 1, Description: 'Apple' },
{ Code: 2, Description: 'Orange' },
{ Code: 3, Description: 'Mango' },
{ Code: 4, Description: 'Guva' }
];
$scope.ddlrhs = '';
$scope.data = [
{ Code: 1, Description: 'Red' },
{ Code: 2, Description: 'Orange' },
{ Code: 3, Description: 'Yellow' },
{ Code: 4, Description: 'Green' }
];
$scope.pushingelement = function (itemCode, colorCode) {
var temp = { "ItemCode": itemCode, "ColorCode": colorCode };
$scope.list.push(temp);
console.log($scope.list);
}
$scope.submit = function () {
$http({
method: "POST",
url: "/Controller/Save",
data:
object:$scope.list
})
}
}
]);
TRY ONCE I HOPE IT HELPS YOU
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>get selected value from dropdownlist in angularjs</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('sampleapp', [])
app.controller('samplecontrol', function ($scope) {
$scope.sample = [{
id: '1',
name: 'Red'
}, {
id: '2',
name: 'Green'
}, {
id: '3',
name: 'Orange'
}, {
id: '4',
name: 'Yellow'
}];
});
</script>
</head>
<body data-ng-app="sampleapp" data-ng-controller="samplecontrol">
<form id="form1">
Select Name:
<select data-ng-model="ddlvalue">
<option value="">--Select--</option>
<option data-ng-repeat="t in sample" value="">{{t.name}}</option>
</select>
</form>
</body>
</html>

AngularJS custom filter for highlight text

I create a filter on a table. Here the code:
<table id="tableText" class="table table-hover table-striped" ng-init="allNews()">
<tr>
<td colspan="5">
<input type="text" placeholder="Ricerca testo" class="form-control" ng-model="inputText">
</td>
</tr>
<tr>
<th>Titolo</th>
<th>Text</th>
<th>Disattivato</th>
<th>Modifica</th>
<th ng-if="!cancelDelete">Elimina</th>
<th ng-if="cancelDelete">Annulla</th>
</tr>
<tr ng-repeat="news in allNews | filter : inputText">
<td>
<div ng-hide="editingData[news.id]"><span ng-bind-html="news | deleteTitle"></span></div>
<div ng-show="editingData[news.id]"><input type="text" class="form-control" ng-model="news.title" /></div>
</td>
<td>
<div ng-hide="editingData[news.id]"><span ng-bind-html="news | deleteText"></span></div>
<div ng-show="editingData[news.id]"><input type="text" class="form-control" ng-model="news.arg" /></div>
</td>
<td>
<div ng-hide="editingData[news.id]"><input type="checkbox" disabled ng-model="news.isDeleted"></div>
<div ng-show="editingData[news.id]"><input type="checkbox" ng-model="news.isDeleted"></div>
</td>
<td>
<div ng-hide="editingData[news.id]"><button id="modify" class="btn btn-primary" ng-click="modify(news, $event)">Modifica</button></div>
<div ng-show="editingData[news.id]"><button id="accept" class="btn btn-success" ng-click="update(news)">Accetta</button></div>
</td>
<td>
<div ng-hide="editingData[news.id]"><button id="delete" class="btn btn-danger" ng-click="delete(news.id)">Cancella</button></div>
<div ng-show="editingData[news.id]"><button id="cancel" class="btn btn-danger" ng-click="cancelModify()">Annulla</button></div>
</td>
</tr>
</table>
The entry on the table is read from db:
$scope.allNews = function () {
var url = '/data_db.asmx/GetAllNews';
var obj = {};
$http.post(url, obj)
.success(
function (response) {
if (response.Error) {
console.log('Server error');
}
else {
$scope.allNews = response.d;
}
})
.error(
function (response) {
console.log('Unkwnow error.');
});
}
I'd like to highlight the text that is search in the 1st row of the table. For now, i receive this error:
angular.js:13920 Error: [filter:notarray] Expected array but received: function ()
but the filter works.
Your problem is that $scope.allNews is a function. When you use it in ng-repeat directive and the directive is evaluated for the first time, your angular will try to examine the allNews property of your $scope as an array.
When the function gets called the first time (which might never happen when angular first encouters the error), it woul overwrite the allNews property with the resulting array of your $http POST request.
Rename either the function or the property and bind your ng-repeat to the array it recieves (and maybe initialize it with an empty array until it is populated by the $http result).
Something like:
$scope.allNews = [];
$scope.getAllNews = function() {
var url = '/data_db.asmx/GetAllNews';
var obj = {};
$http.post(url, obj)
.success(
function (response) {
if (response.Error) {
console.log('Server error');
}
else {
$scope.allNews = response.d;
}
})
.error(
function (response) {
console.log('Unkwnow error.');
});
}
Alternatively try using ngResource, create a service and inject that into your controller. Then populate the array by accessing the service.