generate dropdown using angularJS controller - javascript

I am trying to dynamically add a dropdown using $sce.trustAsHtml() function but I am getting an empty list in the UI. Here is the code:
$scope.addRowtrain = function() {
$scope.locomotivesList = [{"name": "loco1", "value":"1"}, {"name": "loco2", "value":"2"}];
tableData[id] = $sce.trustAsHtml('CTRun'+counter++);
tableData[type] = $sce.trustAsHtml("<select data-ng-model='selectedLoco' data-ng-options='loco.name for loco in locomotivesList'></select>");
}
In the HTML, I want to render it as a table:
<table>
<tbody>
<tr ng-repeat="data in tableData track by $index">
<td ng-repeat="(k, p) in data track by $index"><span ng-bind-html=p>{{p}}</span></td>
</tr>
</tbody>
<a class="btn btn-danger" ng-click="addRowtrain()">Add Run</a>
...
</table
but it is displaying an empty table, please help

you are adding it dynamically you must not pass binding values instead pass Complete JSON object.
It's working with
this example
md-select in angular material

Related

sending html data to view and then sending to controller to update sql database

I have a HTML table where one of the columns value is dynamically added. I have an update button, upon clicking it I want this data to get updated in my sql database. For this, I am planning to first fetch the table data and put into view , then send data to controller and then updating sql.
I am stuck at the first step,
Descibing table below
<thead>
<tr>
<th>ID</th>
<th >Name</th>
<th>Active</th>
<th>Order By</th>
</tr>
</thead>
<tbody>
#if (ViewBag.data != null)
{
foreach (var item in ViewBag.data)
{
<tr>
<td >#item.AutoID</td>
<td #item.Text</td>
<td >#item.Active</td>
<td>#item.OrderBy</td>
</tr>
}
}
</tbody>
</table>
</div>
</div>
<input type="submit" value="Update Preference" class="BtnUpdOrderId" />
</div>
I tried this below js function to fetch the data
$(".BtnUpdOrderId").click(function () {
var tr = $(this).closest('tr');
var id = tr.find('input[name="autoid"]').val();
var text = tr.find('input[name="text"]').val();
var active = tr.find('input[name="active"]').val();
var orderby = tr.find('input[name="orderby"]').val();
alert('type1 : ' + id + ' ' + text + ' ' + active + ' ' + active);
});
but not sure why nothing came in alert
var TableData = new Array();
$('#tblLookup1 tr').each(function (row, tr) {
TableData = TableData + $(tr).find('td:eq(0)').text();
alert(TableData);
});
then tried the above block of code to get data in a variable but still not able to get anything.
Once I get the data I can try sending from view->controller.
So need the following help:
what mistake am I making?
once this is fixed, how to send data to sql? (this is a ado.net based mvc project)
you might want to consider creating a json object:
Creating json object in mvc and returning from controller
then build your table Convert JSON array to an HTML table in jQuery
finally, the update need only post back the json object
https://dontpaniclabs.com/blog/post/2013/02/27/posting-json-data-to-an-mvc-controller-via-ajax/
if you going to use this jason object make sure you use serialization
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-6-0
your have to patch these concepts together but there are a lots of tutorials and examples online so it be a good learning experience
I hope this helps
helpful links:
https://www.sqlshack.com/modifying-json-data-using-json_modify-in-sql-server/
Updating a JSON object using Javascript
https://www.geeksforgeeks.org/how-to-convert-json-data-to-a-html-table-using-javascript-jquery/
create json object from html table using selected colums using jquery

How pick up checkbox result in post method angularjs

I have a table that sets out a list of rules. When the checkboxes are clicked, I need them to take this "true" value and post to an API endpoint. This has been set up, but what I am getting back is that "associated_rule" is undefined.
I have tried setting $scope.associated_rule.selected = true; in my controller, but this still doesn't define the variable and throws up the same error in the console.
Here is my HTML form:
<form name="rules_form" method="post" ng-submit="attach()">
<table class="table table-striped table-hover" ng-model="associated_rules">
<thead>
<th>Rule Types:</th>
<th>Description:</th>
<th>Start Time:</th>
<th>End Time:</th>
<th>Apply Rule to Vehicle:</th>
</thead>
<tr ng-repeat="associated_rule in associated_rules">
<td>#{{ associated_rule.resource_ids.accounts }}</td>
<td>#{{ associated_rule.description }}</td>
<td>#{{ associated_rule.start_time }}</td>
<td>#{{ associated_rule.end_time }}</td>
<td><input type="checkbox" ng-model="associated_rule.selected" aria-label="rule"></td>
</tr>
</table>
<button class="btn btn-primary" ng-click="attach()">Attach</button>
</form>
My Controller event:
$scope.attach = function () {
$scope.associated_rule.selected = true;
var i;
for (i = 0; i < $scope.associated_rule.selected.length; i++) {
//need to create a loop where the true value is picked up and then I can send the data using a POST method. But I'm stuck on this.
}
console.log(the result of the event);
};
For now, I just want the results to console.log, so I can see that the event is creating the loop and displaying the results. After that, I should be OK.
Any help would be much appreciated.
I have fixed this by defining the $scope.rule as an empty array and setting the $scope.rule.selected to "false" by default.
Great! step one! But the checkboxes are ALL selecting when you click A checkbox - think this may be the ng-repeat causing me a pain in the backside.
$scope.rule = [];
$scope.rule.selected = false;
So, how do I ensure that only the checkboxes set that I select and not all at once?
Fixed this too; as the above was just making the entire array selected; as i wasn't drilling down into the array. This did it:
ng-model="rules.selected[associated_rule.id]"
by modelling the a rule within that defined array, it shows up when testing. Brill. :)
By mistake you are changing the value of your check box on clicking the button:
$scope.associated_rule.selected = true;
This will give the current value, selected or not selected
$log.log($scope.associated_rule.selected);

How to get Button label in AngularJS?

I have following lines of code in my AngularJS project.
<div ng-show="update">
<table border="1">
<tr ng-repeat="x in names">
<td>{{ x.uname}}</td>
<td>{{ x.upass}}</td>
<td><button ng-model="index" ng-click="show()"
ng-value="{{x.index}}">Edit</button></td>
</tr>
</table>
When Particular button is clicked I want to retrieve that button label.
For that I have written code in Show function:
var v = $scope.index;
alert(v);
But alert box is displaying "Undefined" when i click on button.
Please suggest me where I am wrong??
Thanks in advance
What about providing your value as an argument to the onclick function ?
<div ng-show="update">
<table border="1">
<tr ng-repeat="x in names">
<td>{{ x.uname}}</td>
<td>{{ x.upass}}</td>
<td><button ng-click="show(x.index)">Edit</button></td>
</tr>
</table>
and then
function show(id){
alert(id);
}
This should works. Also ng-model does not work on button.
under ng-click = show(item) - this gives the particular item object.
function show(obj){ console.log(obj)}
this function give the particular clicked obj from view.
ng-model doesn't work on button.
You can pass the index of the repeat iteration to the show method like this:
<button ng-click="show($index)" ...
and use it like this:
function show(i){
var v = names[i];
alert(v);
}
You can see it in action here: PLNKR DEMO
NOTE: if you are passing the index to the backend service the index may not match up with the actual array if you are using a filter in your view to alter/reduce the ng-repeat expression
Another option as pointed out by #Grundy is to just pass the object back, which saves you the step of having to access it from the array... (note: this is the suggested best practice)
I am assuming that you want the button label that you have clicked on and the index of it in the list provided. Here is what you can do.
<div ng-repeat="buttonId in testdata2">
<button ng-bind="buttonId" ng-click="clickedMe(buttonId, $index)"></button>
</div>
$scope.clickedMe = function(buttonId, index) {
console.log(buttonId + " - " + index);
};
Have your files in local and run them.

AngularJS - Using variable name in JSON selector

I have a table using angularjs where I want to loop through an array to print specific headers from a json object. The header prints out fine, but the problem comes when I try to use a variable from my nested ng-repeat as a json selector. If you replace the inner ng-repeat with the commented section below it, it will work.
Table:
<table>
<thead>
<th ng-repeat="column in tableHeader">{{column}} <a ng-click="sort_by(column);"><i class="glyphicon glyphicon-sort"></i></a></th>
</thead>
<tbody>
<tr ng-repeat="data in filtered>
<td ng-repeat="column2 in tableHeader">{{data.column2}}</td>
<!-- <td>{{data.Environment}}</td>
<td>{{data.HostIP}}</td>
<td>{{data.ServiceName}}</td>
<td>{{data.Status}}</td>
<td>{{data.StartTime}}</td>
<td>{{data.Capacity}}</td>
<td>{{data.Txn}}</td>
<td>{{data.Errors}}</td>
<td>{{data.Build}}</td>
<td>{{data.Project}}</td>
<td>{{data.Author}}</td>
<td>{{data.ModifyDate}}</td>
<td>{{data.Port}}</td>
<td>{{data.BasePath}}</td> -->
</tr>
</tbody>
</table>
Array located in controller:
$scope.tableHeader = ['Environment', 'HostIP', 'Status', 'ServiceName', 'StartTime', 'Capacity', 'Txn', 'Errors', 'Build', 'Project', 'Author', 'ModifyDate', 'Port', 'BasePath'];
I think you're looking for {{data[column2]}}. Since column2 is just the string value of the property you want, treat data like an associative array in this case to get the property you're trying to display.
column2 was created by the ng-repeat and is what you want. Note {{column2}}:
<td ng-repeat="column2 in tableHeader">{{column2}}</td>

Using $index for ng-model

I am building a SPA where one can add a table-row on button-click:
<!-- Table -->
<table>
<tr>
<th>Lieferscheinnummer</th>
<th>Stück</th>
</tr>
<tr ng-repeat="position in positions">
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
</table>
<!-- button -->
<span ng-click="addPosition()"></span>
Controller
$scope.positions = ['1'];
$scope.addPosition = function(){
$scope.positions.push( $scope.positions.length + 1 );
}
Now I have to apply an unique ng-model to each <td> of every row in order to send the given input to my database.
I searched for a solution and stumbled over ng-repeat's $index.
Unfortunately, $index seems to be not available for element attributes:
<tr ng-repeat="position in positions">
<td><input type="text" ng-model="{{$index +1}}"></td> <!-- does not work -->
<td><input type="text"></td>
</tr>
How would I apply an unique ng-model to each row while using ng-repeat?
You could change your model. Currently, you are using the ng-repeat like a counter. You have a model that stores the elements - you are not using the elements in anyway, just making use of the number of elements in the list and looping that many times.
What you could instead do is have a list of unique models itself.
Considering that you are using it inside a table, each entry could have an ID field to uniquely identify each row.
Thus, your model would look something like this:
//Will contain the data entered in the table
$scope.tableData = [
{
id: 1,
data: ""
},
{
id: 2,
data: ""
}
];
//Will keep track of the last used ID
$scope.currentId = 2;
//Will add a record to the table each time it is called
$scope.addRecord = function () {
var newRecord = {
id: $scope.currentId++;
data: ""
};
$scope.tableData.push(newRecord);
};
In your view, you can now use tableData to loop over the actual data itself rather than the count of the records:
<tr ng-repeat="entry in tableData">
<td>
<input type="text" ng-model="entry.data">
</td>
</tr>
For another input, you could simply add another attribute to each record. ng-repeat will create a scope for each record so entry.data will always point to the data attribute for the record located at that row.
Note: For an ID, you may have to use another approach of generating unique Ids for large amounts of records. Simply increment a counter will not be the best approach.

Categories

Resources