Consider I have a list of objects like -
var configs = [{
id: "1",
name: "config1"
},
{
id: "2",
name: "config2"
}
];
I use the following to search through the config list and bind the selected config to another variable called changed_config.
<table style="width:900px;">
<tr>
<th style="width:500px; margin:50px">Config Name</th>
<th style="width:150px;">Config Value</th>
</tr>
<tr ng-repeat="changed_config in changed_configs">
<td>
<input type="text" class="form-control" ng-model="changed_config.id" list="names">
<datalist id="names">
<option ng-repeat="option in configs | filter:search | limitTo:30" ng-value="option.name"> {{option.name}}
</option>
</datalist>
<td>
<input type="text" class="form-control" ng-model="changed_config.value">
</td>
</tr>
</table>
<div class="row">
<button type="button" id="add-reward-grp-btn" ng-click="addConfig()"
class="btn btn-primary">Add Config
</button>
</div>
Controller Code(Not complete code, just relevant snippets):
var app = angular.module("drs_scheduler_app", []);
app.controller("CreateSchedulerJob", function ($scope, $http) {
$scope.changed_configs = [];
$scope.configs = [{
id: "1",
name: "config1"
},
{
id: "2",
name: "config2"
}
];
$scope.addConfig = function () {
var config = {
"id": "",
"value": ""
};
$scope.changed_configs.push(config);
console.log(config);
console.log(JSON.stringify($scope.changed_configs));
}
}
Currently the code displays and binds the name of the selected config to the changed_config variable. But I need the id to be bound to the changed_config variable and the name to be displayed in the html.
If I change the <option> to use id, then id will be displayed.
How do I bind one property to a variable but show another in the html??
Here is the solution you needed,
Procedure:
When an option is selected from datalist I m checking for that
change
That change is observed through input on which datalist is added
On that input change i,e when option is selected I m assigning that
id to id key of respective changed_config
That is inturn displayed in second textbox
It works for dynamic
// Code goes here
function cntryController($scope) {
$scope.LoadSessionData=function(val)
{
console.log(val);
};
$scope.changed_configs = [];
$scope.configs = [{
id: "1",
name: "config1"
},
{
id: "2",
name: "config2"
}
];
$scope.addConfig = function () {
var config = {
"id": "",
"value": ""
};
$scope.changed_configs.push(config);
console.log(config);
console.log(JSON.stringify($scope.changed_configs));
}
$scope.test = function(data, index){
console.log(data)
var newArray = $scope.configs.filter(function (config) {
return config.name == data;
});
console.log(newArray)
if(newArray.length){
var new_changed_config = $scope.changed_configs[index];
new_changed_config.id = newArray[0].id;
}
}
}
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<div ng-app="" ng-controller="cntryController">
<table cellspacing="10" cellpadding="10">
<tr>
<th>Config Name</th>
<th>Config Value</th>
</tr>
<tr ng-repeat="changed_config in changed_configs">
<td>
<input type="text" class="form-control" ng-model="changed_config.name" list="names" ng-change="test(changed_config.name, $index)">
<datalist id="names">
<option ng-repeat="option in configs | filter:search | limitTo:30" value={{option.name}}>{{option.name}}
</option>
</datalist>
</td>
<td>
<input type="text" class="form-control" ng-model="changed_config.id"/>
</td>
</tr>
</table>
<div class="row">
<button type="button" id="add-reward-grp-btn" ng-click="addConfig()" class="btn btn-primary">Add Config</button>
</div>
</div>
</html>
Please run the above snippet
Here is a working DEMO
Related
I have selection tag with three options:important,middle important, not so important; and on each selection I want to show only those elements from my table which contains this data.
On the other hand I want to add logic which will tell me that certain tr is show or hide ( I want to add showed materials to array)
Here is my code , how should I implement this logic?
<select id="mySelector" class="styled-select slate" style="width:280px; height:35px">
<option value='important'>აირჩიე</option>
<option value='very important'>very important</option>
<option value='middle important'>middle important</option>
<option value='not so important'>not so important</option>
</select>
//selection code
$(document).ready(function($) {
$('#mySelector').change( function(){
var selection = $(this).val();
$('table')[selection? 'show' : 'hide']();
if (selection) {
$.each($('#myTable tbody tr'), function(index, item) {
$(item)[$(item).is(':contains('+ selection +')')? 'show' : 'hide']();
});
}
});
});
$scope.selectAll = function(){
document.querySelector('#myTable1').style.display = 'block';
for (var i = 0; i < $scope.realJsonArray.length; i++) {
var item = $scope.realJsonArray[i];
console.log(item.id+"id======================");
issync1(item);}
};
<tr id="input1">
<td><input type="checkbox" ng-change="sync(selected[item.id],item)" ng-checked="isChecked(item.id)" name="checkData" ng-model="selected[item.id]" ng-false-value="undefined" /></td>
<td>{{item.id}}</td>
<td>{{item.organizationNameEN}}</td>
<td>{{item.organizationNameGE}}</td>
<td>{{item.priority}}</td>
<td><button class="btn btn-default btn-xs" ng-click="toggle($index)"><span class="glyphicon glyphicon-eye-open"></span></button></td>
</tr>
p.s my table tag id is myTable1
You can use $.toggleClass():
$(function() {
$('input').on('change', function(e) {
$('p').toggleClass('hide', this.checked);
});
});
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type='checkbox'/>Show/Hide</label>
<p>This is para</p>
function which will tell me if row is selected ( if it is selected it
can return true and false in other way for example)
Yes, you can lookup using input checkbox which you have for each row.
Option 1: finding using checkboxes itself
$(function() {
$('button').on('click', function() {
var rows = $('input[name=checkData]:checked').parents('tr');
console.log('checked rows', 0 !== rows.length);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr id='input1'>
<td>
<input name="checkData" type='checkbox' />
</td>
</tr>
<tr id='input2'>
<td>
<input name="checkData" type='checkbox' checked='' />
</td>
</tr>
<tr id='input3'>
<td>
<input name="checkData" type='checkbox' />
</td>
</tr>
</table><button>Check</button>
Refer following code may this would meet you requirement !!
<table>
<tr><td></td><td>id</td> <td>name</td> <td>address</td> <td>classA</td> <td>classB</td></tr>
<tr ng-repeat="employee in employees">
<td><input type="checkbox" ng-model="employee.checked" ng-true-value="1" ng-false-value="0"></td>
<td>{{employee.id}}</td>
<td>{{employee.name}}</td>
<td>{{employee.address}}</td>
<td><input type="checkbox" ng-model="employee.classA"></td>
<td><input type="checkbox" ng-model="employee.classB"></td>
</tr>
</table>
app.controller('MainCtrl', function($scope) {
$scope.employees = [
{ id:"1", name: "A", address: "A1", classA: true, classB: true },
{ id:"2", name: "B", address: "A2", classA: false, classB: true },
{ id:"3", name: "C", address: "A3", classA: true, classB: false },
{ id:"4", name: "D", address: "A4", classA: false, classB: true },
{ id:"5", name: "E", address: "A5", classA: false, classB: true },
];
$scope.getSelected = function () {
var ar = $scope.employees.filter(
function (value) {
if (value.checked == 1) {
return true;
} else {
return false;
}
}
);
return ar;
};
});
Using Knockout JS:
I have a requirement as.
I have a table with 2 static columns where each has a text-box. I also have a add row button outside the table and one remove row button along each row.
When the user clicks add row it adds a row to the table and I can see two columns with textbox in each. User can add more rows if required by clicking add row and click remove row to remove rows.
This all has been setup and works fine as :
https://jsfiddle.net/aman1981/xmd1xobm/14/
My issue is there is also an Get Columns button. When the user clicks this button I fetch a list of columns and want to add these columns with headers b/w the already existing columns of the table.Each of these columns also need to have a textbox as well.
For ex I would the list of columns as:
var columnsList = 'name, address, zip';
I am not sure how to add columns dynamically. Would appreciate inputs.
Here is the setup of my table:
<table class="table table-bordered">
<thead class="mbhead">
<tr class="mbrow">
<th>SIID</th>
<th>Comment</th>
</tr>
</thead>
<tbody data-bind="foreach: data">
<tr>
<td>
<input type="text" data-bind="text: SIID" class="form-control textbox" />
</td>
<td>
<input type="text" data-bind="text: Comment" class="form-control textbox" />
</td>
<td>
<input type="button" value="Remove Row" data-bind="click: $parent.removeRow" class="btn btn-danger" />
</td>
</tr>
</tbody>
<div class="col-xs-12 col-sm-6">
<input type="button" value="Add Row" class="btn btn-primary" data-bind="click: addRow" />
<input type="button" value="Get Columns" class="btn btn-primary" data-bind="click: addColumns" />
</div>
Anyone?
Nice for you i have a dynamic table component from my previous project:
var observable = ko.observable;
var pureComputed = ko.pureComputed;
var observableArray = ko.observableArray;
var unwrap = ko.unwrap;
var data = observableArray([{
a: 123,
b: 234,
c: 345
},{
a: 1231,
b: 2341,
c: 3451
},{
a: 1232,
b: 2342,
c: 3425
},{
a: 1233,
b: 2343,
c: 3453
}]);
var columns = observableArray([{
field: "a",
displayName: "A"
},{
field: "b",
displayName: "B (i can even change the title)"
}])
function viewModel(params) {
var paramColumns = params.columns;
var paramData = params.data;
var paramFieldKey = params.fieldKey || "field";
var paramDisplayNameKey = params.displayNameKey || "displayName";
var koColumnHeaders = pureComputed(function () {
var columns = paramColumns();
var columnHeaders = [];
var fieldKey = unwrap(paramFieldKey);
var displayNameKey = unwrap(paramDisplayNameKey);
for (var i in columns) {
var column = columns[i];
columnHeaders.push({
field: column[fieldKey],
displayName: column[displayNameKey]
})
}
return columnHeaders;
})
var koRows = pureComputed(function () {
var data = paramData();
var columns = paramColumns();
var fieldKey = unwrap(paramFieldKey);
var rows = [];
for (var i in data) {
var datum = data[i];
var cells = []
var row = {
entity: data,
cells: cells
};
for (var j in columns) {
var column = columns[j];
cells.push(datum[column[fieldKey]] || "");
}
rows.push(row);
}
return rows;
});
return {
rows: koRows,
columns: koColumnHeaders,
}
}
ko.applyBindings(new viewModel({
data: data,
columns: columns
}))
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table class="table table-bordered" border="1">
<thead>
<tr data-bind="foreach: columns">
<th data-bind="text: displayName">
</th>
</tr>
</thead>
<tbody data-bind="foreach: rows">
<tr>
<!-- ko foreach: cells -->
<td class="" data-bind="text: $data"></td>
<!-- /ko -->
</tr>
</tbody>
</table>
I was able to resolve this using the post at:
Knockout JS: Get Textbox data from Table under for-each binding
Here is my code:
(function() {
var ViewModel = function() {
var self = this;
self.valuesData = ko.observableArray();
self.columns = ko.computed(function() {
if (self.valuesData().length === 0)
return [];
return ValuesData.columns;
});
self.addRow = function() {
self.valuesData.push(new ValuesData());
};
self.Save = function() {
alert('Data:')
};
self.removeRow = function(data) {
self.valuesData.remove(data);
};
}
// Dynamic values.
var ValuesData = function(siid, comment) {
var self = this;
// Add observables dynamically for all relevant columns.
for (var i = 0; i < ValuesData.columns.length; i++) {
var column = ValuesData.columns[i];
self[column.Property] = ko.observable(column.InitialValue)
}
};
// Basic column definition.
ValuesData.columns = [{
Caption: 'SIID',
Property: 'SIID',
InitialValue: undefined
},
{
Caption: 'Column 1',
Property: 'Col1',
InitialValue: undefined
},
{
Caption: 'Column 2',
Property: 'Col2',
InitialValue: 'banana'
},
{
Caption: 'Comment',
Property: 'Comment',
InitialValue: undefined
}
]
vm = new ViewModel()
ko.applyBindings(vm);
// add initial row.
vm.addRow();
})();
Here is the html part:
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-
min.js"></script>
<br><br>
<table>
<thead>
<!-- NEW: use ko foreach with 'as' to have an alias for accessing $data. -->
<tr data-bind="foreach: { data: columns, as: 'column'}">
<th> <span data-bind="text: column.Caption"></span>
</th>
</tr>
</thead>
<tbody data-bind="foreach: { data: valuesData, as: 'rowData'}">
<tr data-bind="foreach: { data: $parent.columns, as: 'column' }">
<!-- NEW: bind to the corresponding property/observable in ValuesData -->
<td><input type="text" class="form-control textbox" data-bind="textInput:
rowData[column.Property]" /> </td>
</tr>
<tr>
<td>
<input type="button" value="Remove Row" data-bind="click:
$parent.removeRow" class="btn btn-danger" />
</td>
</tr>
</tbody>
I want to call the controller function from view.
This my view:
<body>
<div ng-app="appTable">
<div ng-controller="Allocation">
<button ng-click="add()"> Add </button>
<button ng-click="remove()">remove</button>
<table>
<th>
<td>Date</td>
<td>Project</td>
<td>Release</td>
<td>Feature</td>
<td>Module name</td>
<td>Hours spent</td>
<td>Comment</td>
</th>
<tr ng-repeat="data in dataList">
<td><input type="checkbox" ng-model="data.isDelete"/></td>
<td>
<input type="text"
datepicker
ng-model="data.date" />
</td>
<td><input type="text" ng-model="data.dept"/></td>
<td>
<select ng-model="data.release" ng-options="x for x in range">
</select>
</td>
<td>
<select ng-model="data.feature" ng-options="x for x in feature">
</select>
</td>
<td>
<input type = "text" ng-model = "data.modulename">
</td>
<td>
<select ng-model="data.hours" ng-options="x for x in hours">
</select>
</td>
<td>
<input type = "text" ng-model = "data.comment">
</td>
</tr>
</table>
<button ng-click="Submit()">Submit</button>
<table>
<tr ng-repeat="data in displayList">
<div ng-controller="Allocation as vm">
<div>{{vm.postdata(data.date)}}</div>
</div>
<p>Output Message : {{msg}}</p>
<p>StatusCode: {{statusval}}</p>
<p>Status: {{statustext}} </p>
<p>Response Headers: {{headers}} </p>
<td>
<p>{{data.date}}</p>
</td>
<td>
<p>{{data.dept}}</p>
</td>
<td>
<p>{{data.release}}</p>
</td>
<td>
<p>{{data.feature}} </p>
</td>
<td>
<p>{{data.modulename}}</p>
</td>
<td>
<p>{{data.hours}}</p>
</td>
<td>
<p>{{data.comment}}</p>
</td>
</td>
</tr>
</table>
</div>
</div>
</body>
This is script.
<script>
var app = angular.module("appTable", []);
app.controller("Allocation", function($scope) {
$scope.hours = ["1", "2", "3"];
$scope.range = ["1", "2", "3"];
$scope.feature = ["UT", "FSDS", "Coding/Devlopment", "QA"];
$scope.dataList = [{
date: '17/07/2016',
dept: 'OneCell',
release: '1',
feature: "UT",
modulename: "Redundancy",
hours: "1",
comment: "Add extra information"
}];
$scope.add = function() {
var data = {};
var size = $scope.dataList.length;
if (!size) {
$scope.dataList = [{
date: '17/07/2016',
dept: 'OneCell',
release: '1',
feature: "UT",
modulename: "Redundancy",
hours: "1",
comment: "Add extra information"
}];
} else {
size = size - 1;
data.date = $scope.dataList[size].date;
data.dept = $scope.dataList[size].dept;
data.release = $scope.dataList[size].release;
data.feature = $scope.dataList[size].feature;
data.modulename = $scope.dataList[size].modulename;
data.hours = $scope.dataList[size].hours;
data.comment = $scope.dataList[size].comment;
$scope.dataList.push(data);
}
};
$scope.Submit = function() {
$scope.test = "Submit is pressed...";
$scope.displayList = [];
angular.forEach($scope.dataList, function(v) {
if (!v.isDelete) {
$scope.displayList.push(v);
}
});
$scope.dataList.splice(0);
};
$scope.remove = function() {
var newDataList = [];
angular.forEach($scope.dataList, function(v) {
if (!v.isDelete) {
newDataList.push(v);
}
});
$scope.dataList = newDataList;
};
$scope.postdata = function(date) {
var data = {
date: date,
};
$http.post('/add_status/', data).then(function(response) {
if (response.data)
$scope.msg = "Post Data Submitted Successfully!";
}, function(response) {
$scope.msg = "Service not Exists";
$scope.statusval = response.status;
$scope.statustext = response.statusText;
$scope.headers = response.headers();
});
};
});
app.directive("datepicker", function() {
function link(scope, element, attrs, controller) {
// CALL THE "datepicker()" METHOD USING THE "element" OBJECT.
element.datepicker({
onSelect: function(dt) {
scope.$apply(function() {
// UPDATE THE VIEW VALUE WITH THE SELECTED DATE.
controller.$setViewValue(dt);
});
},
dateFormat: "dd/mm/yy" // SET THE FORMAT.
});
}
return {
require: 'ngModel',
link: link
};
});
</script>
As you can see in the view I have called the postdata function of the controller.This function internally uses msg variable.But view is not printing value of this variable.I am very new to Aj. Please help.
You need to make following changes:
Remove ng-controller="Allocation as vm", as you already defined controller above., and you not using this syntax in controller.
after you removed as vm, then no need to vm. calls.
you need to inject $http in your controller., to make API call
See this fiddle demo, I logged dummy text in console for each `submit click.
and to make single call on submit, See this Fiddle
You should return a value in the function or add a scope variable to be shown in the controller's div, because right now you are not showing anything.
<div ng-controller="Allocation as vm">
<div>{{vm.postdata(data.date)}}</div>
<p>Output Message : {{msg}}</p>
<p>StatusCode: {{statusval}}</p>
<p>Status: {{statustext}} </p>
<p>Response Headers: {{headers}} </p>
</div>
Anyway, you should not run procedural function in this way. Bind it to an event, ng-click or something.
And do not create other than td or th child elements in tr.
This is the proper html table structure:
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
</table>
I have a button that currently passes the selected value to the removeContract().
<td class="col-md-1" colspan="1" style="text-align: center; vertical-align: middle;">
<button class="btn btn-primary" data-ng-click="removeContract(ctrl.selectValue, contractIndex)"> <= </button>
</td>
<td class="col-md-5" colspan="5">
<label class="control-label">{{item.fields[132].displayName}}</label>
<select size="5" ng-model="ctrl.selectValue">
<option data-ng-repeat="contract in contracts">{{contract.CONT_ORDNO}} - {{contract.SUPP_NAME}}[{{contract.SUPP_NUM}}]</option>
</select>
</td>
However, I need to send back the actual current contract model, called 'contract' above. The function's 1st parameter needs to be the currently selected contract. How would I achieve this?
Some suggestions as per the current code :
Instead of passing whole {{contract.CONT_ORDNO}} - {{contract.SUPP_NAME}}[{{contract.SUPP_NUM}}] into the ng-model just pass the contract.CONT_ORDNO to identify the selected data from the dropdown.
<option data-ng-repeat="contract in contracts" value="contract.CONT_ORDNO">{{contract.CONT_ORDNO}} - {{contract.SUPP_NAME}}[{{contract.SUPP_NUM}}]</option>
As we already have contracts array of objects inside the controller.Hence, no need to pass the second parameter inside the removeContract function.
<button class="btn btn-primary" data-ng-click="removeContract(ctrl.selectValue)"> <= </button>
Based on the selected value we can remove the contract object from the contracts array inside removeContract function with the help of Array filter() method.
DEMO
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
$scope.contracts = [
{
"CONT_ORDNO": "1",
"SUPP_NAME": "alpha",
"SUPP_NUM": "0001"
},
{
"CONT_ORDNO": "2",
"SUPP_NAME": "beta",
"SUPP_NUM": "0002"
},
{
"CONT_ORDNO": "3",
"SUPP_NAME": "gaama",
"SUPP_NUM": "0003"
},
{
"CONT_ORDNO": "4",
"SUPP_NAME": "xyz",
"SUPP_NUM": "0004"
}
];
$scope.removeContract = function(selectedVal) {
var removedObj = $scope.contracts.filter(function(item) {
return item.CONT_ORDNO != selectedVal;
});
console.log(removedObj);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<td class="col-md-1" colspan="1" style="text-align: center; vertical-align: middle;">
<button class="btn btn-primary" data-ng-click="removeContract(ctrl.selectValue)"> <= </button>
</td>
<td class="col-md-5" colspan="5">
<label class="control-label">{{item.fields[132].displayName}}</label>
<select size="5" ng-model="ctrl.selectValue">
<option data-ng-repeat="contract in contracts" value="{{contract.CONT_ORDNO}}">{{contract.CONT_ORDNO}} - {{contract.SUPP_NAME}}[{{contract.SUPP_NUM}}]</option>
</select>
</td>
</div>
I'm new to angular and js. I did a table (just a header) and a button. When I click the button a new row line is added. Every cell of that row is a form text field. Everithing works fine. Now I'm trying to do a second button, when I click it must iterate over the rows and validate the fields. I'm not finding any documentation about that... so i'm not sure if this mettod (add a new row with a button) is appropiate. That's how I did it:
index.html this contains angular and my script, also contains the routes:
<html ng-app="assets">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="sources/js/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.10/angular-route.min.js"></script>
<script>
var assets = angular.module('assets', ['ngRoute']);
assets.config(function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'home.html'
}).
when('/:tipusactius', {
templateUrl: 'tipusactius.html',
controller: 'TipusActiusCtrl'
}).
when('/:tipusactius/alta', {
templateUrl: 'tipusactius-alta.html',
controller: 'AfegirTipusActiusCtrl'
}).
otherwise({
redirectTo: '/'
});
});
assets.controller('TipusActiusCtrl', function ($scope, $http){
$http.get('http://10.0.203.73/WS/ws.php/tipusactius/').success(function(data) {
$scope.tipus_actius = data;
});
// Ordena taula per id desc
$scope.sortField = 'idtipus_actius';
$scope.reverse = false;
});
assets.controller('AfegirTipusActiusCtrl', function ($scope, $http){
// Camps formulari text pla
$scope.nomAtribut = "<input type='text' name='firstname'>";
$scope.mida = "<input type='number' name='firstname'>";
$scope.obligatori = "<input type='checkbox' name='vehicle' value='yes'>";
// Construeix combo
$http.get('http://10.0.203.73/WS/ws.php/getCombo/1').success(function(data) {
$scope.options = data;
});
$scope.atributs = [];
$scope.addField = function() {
$scope.atributs.push($scope.atributs.length);
};
$scope.prioritat = $scope.atributs.length;
});
assets.directive('compile', compile);
function compile($compile)
{
return {
restrict: 'A',
replace: true,
link: linkFunction
};
function linkFunction(scope, element, attrs)
{
scope.$watch(
function (scope)
{
return scope.$eval(attrs.compile);
},
function (value)
{
element.html(value);
$compile(element.contents())(scope);
}
);
}
}
</script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<div class="container" ng-view></div>
</body>
</html>
And this is the view where the table is(tipusactius-alta):
<div class="row">
<div class="col-md-8" ng-controller="AfegirTipusActiusCtrl">
<button ng-click="addField()">Nou atribut</button>
<div>
<table class="table">
<tr>
<td>Nom atribut</td>
<td>Tipus</td>
<td>Mida</td>
<td>Prioritat</td>
<td>Obligatori</td>
</tr>
<tr ng-repeat="atribut in atributs">
<td compile="nomAtribut"></td>
<td>
<select id="tipus">
<option ng-repeat="option in options" value="{{option.idvalors_combo}}">{{option.valor}}</option>
</select>
</td>
<td compile="mida"></td>
<td>
<select id="prioritat">
<option ng-repeat="p in prioritat" value="{{p}}">{{p}}</option>
</select>
</td>
<td compile="obligatori"></td>
</tr>
</table>
</div>
</div>
</div>
</div>
I'm not sure if this has been a good idea. I would like to find a way to iterate over the rows to read cell values, and if the values of all cells from all the rows is ok submit the values to the web service but I have no idea. Any help will be great.
You don't actually need to manipulate html directly. Just use ng-repeat over your data collection. Button should add new items to that collection and angular will create new table row in the document.
I've created small sample here: http://jsfiddle.net/Lvc0u55v/252/
var myApp = angular.module('myApp', []);
myApp.controller('tableCtrl', function($scope) {
$scope.dataTable = [{
"name": "Alex",
"lastName": "Karlov",
"age": 23,
"sex": 1
}];
$scope.options = [{
"value": 1,
"title": "Male"
}, {
"value": 2,
"title": "Female"
}];
$scope.addRow = function() {
var newItem = {
name: "",
lastName: "",
age: "",
sex: ""
}
$scope.dataTable.push(newItem);
};
});
And this is the html (I've created it based on yours code):
<div class="col-md-8" ng-controller="tableCtrl">
<button ng-click="addRow()">Add row</button>
<div>
<table class="table">
<tr>
<td>#</td>
<td>Name</td>
<td>Last Name</td>
<td>Age</td>
<td>Sex</td>
</tr>
<tr ng-repeat="item in dataTable">
<td>{{ $index + 1 }}</td>
<td>
<input type="text" ng-model="item.name" />
</td>
<td>
<input type="text" ng-model="item.lastName" />
</td>
<td>
<input type="text" ng-model="item.age" />
</td>
<td>
<select ng-options="option.value as option.title for option in options" ng-model="item.sex"></select>
</td>
</tr>
</table>
</div>
</div>
In that sample I've put all my data into dataTable variable. When I want to add one more row, I just need to add new empty object (or with predefined values) into dataTable collection. Angular will do the trick.