Angular ng-repeat dynamic - javascript

See this plunker
In jQuery I can get the text of its td and put it in an alert but how can I make it in Angular? Should I make it an javascript native?
This is the script
var app = angular.module('plunker',[]);
app.controller('ctrl',function($scope){
$scope.edit = function(){
alert("ID = " + $scope.id + "\n NAME = " + $scope.name);
};
$scope.items = [
{id:"1",name:"name 1"},
{id:"2",name:"name 2"},
{id:"3",name:"name 3"}
];
});
The HTML
<body ng-controller="ctrl" ng-app="plunker">
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>edit</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in items">
<td ng-model="x.id">{{x.id}}</td>
<td>{{x.name}}</td>
<td><button ng-click="edit()">edit</button></td>
</tr>
</tbody>
</table>
</body>
P.S
The ng-repeat is dynamic so how can I get the value of it?

Just pass the value to the edit function as parameter,
<td><button ng-click="edit(x)">edit</button></td>
and then function would be,
$scope.edit = function(x){
console.log("Id is",x.id);
}
DEMO
var app = angular.module('plunker',[]);
app.controller('ctrl',function($scope){
$scope.edit = function(){
alert("ID = " + $scope.id + "\n NAME = " + $scope.name);
};
$scope.items = [
{id:"1",name:"name 1"},
{id:"2",name:"name 2"},
{id:"3",name:"name 3"}
];
$scope.edit = function(x){
console.log("$$Id is",x.id);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-controller="ctrl" ng-app="plunker">
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>edit</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in items">
<td ng-model="x.id">{{x.id}}</td>
<td>{{x.name}}</td>
<td><button ng-click="edit(x)">edit</button></td>
</tr>
</tbody>
</table>
</body>

Make your function edit() take a variable and then pass it in:
$scope.edit = function(obj){
alert("ID = " + obj.id + "\n NAME = " + obj.name);
};
and then:
<td><button ng-click="edit(x)">edit</button></td>

You can create an array $scope.itemModel of size items.length in your controller and set the model in markup using $index on $scope.itemModel[$index] and then access the item by passing $index to the handler from your controller.

Related

how to send object from html ng-repeat to js function

I am getting data from db and put it in a scope, then iterate on these data by ng-repeat in html.
what i am trying to do is to send the selected object when the user check on a checkbox to get another data based on an id for example . i tried to use ng-model and ng-change on the checkbox but it sends only true or false .
HTML
<div id="frame" class="widget-content" style="height:50vh; overflow:auto;">
<table style="font-size: 12px;display: inline-block;">
<thead>
<tr>
<th>Check</th>
<th>Group Code</th>
<th>Group Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="g in Groups | unique : 'Group_code'"
ng-click="showInEdit(g)"
ng-class="{selected:g === selectedRow}">
<td><input type="checkbox" ng-model="g"
ng-true-value="g" ng-change="Getrequest2(g)"/>
<td>{{g.Group_code}}</td>
<td>{{g.group_name_latin}}</td>**
</tr>
</tbody>
</table>
<table style="font-size: 12px; float: left;">
<thead>
<tr>
<th>Check</th>
<th>Item Code</th>
<th>Item Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="i in items | unique : 'Item_code'"
ng-click="showInEdit(i)"
ng-class="{selected:i === selectedRow}">
<td><input type="checkbox" />
<td>{{i.Item_code}}</td>
<td>{{i.ITEM_NAME_LATIN}}</td>
</tr>
</tbody>
</table>
</div>
angularjs
$scope.Getrequest1 = function (g) {
//console.log(g);
$scope.typecd = g.TypeCode;
$scope.ShowLoading('slow');
LOASrv.GetGroup("LOAApprovalSetup/GetGroup" +
"?typ=" + g.TypeCode +
'&hospid=' + $scope.hospitalid +
'&userky=' + $scope.userkey
).then(function (response) {
$scope.Groups = (response.data);
$scope.HideLoading('slow');
})
}
$scope.Getrequest2 = function (i) {
console.log(i);
$scope.ShowLoading('slow');
LOASrv.GetItem("LOAApprovalSetup/GetItem" +
"?typ=" + $scope.typecd +
'&hospid=' + $scope.hospitalid +
'&userky=' + $scope.userkey +
'&groupcd=' + i
).then(function (response) {
$scope.items = (response.data);
$scope.HideLoading('slow');
})
}
You’re assigning ‘g’ object to checkbox ng-model.
This changes the value of ‘g’ from object to boolean on checkbox select.
That’s why you’re getting true/false
Change ng-model=“g.someBooleanName” and try

Angular search for combined key

Say you have the following object:
var user: {firstname: 'Marc', lastname:'Ras', age:30};
You have alot of these objects in an array called: user_array
Now you wish to display them in a table so you create your table:
<table>
<thead>
<th>Full name</th>
<th>Age</th>
</thead>
<tbody>
<tr ng-repeat="user in user_array">
<td>{{user.firstname + ' '+user.lastname}}</td>
<td>{{user.age}}</td>
</tr>
</tbody>
</table>
Now you wish to create an input field where you can search for a user's full name:
And here is kinda ends for me :S how is it possible to search for a combinded key? normally you would have:
<input type="text" ng-model="search.fieldname" />
However you cant do that here since the field is combined of two fieldnames?
add this to your controller
$scope.filterNameLastName = function (user) {
var fullname = user.firstname + ' '+ user.lastname;
if(fullname == $scope.searchParamater)
return true;
else
return false;
};
and add filter to ng-repeat
<table>
<thead>
<th>Full name</th>
<th>Age</th>
</thead>
<tbody>
<tr ng-repeat="user in user_array | filter:filterNameLastName ">
<td>{{user.firstname + ' '+user.lastname}}</td>
<td>{{user.age}}</td>
</tr>
</tbody>
</table>
This should give you an idea on how custom filters work. I haven't tested the code so you may have to do some modifications.

How to pass array to html in angularjs1.5.5

How can I pass array Json data from angularjs Controller to html.
Here is my html
<body ng-app="bookApp">
<div ng-controller="bookListCtr">
<table>
<thead>
<tr>
<th>something</th>
<th>something</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items">
<td><( item.id )></td>
</tr>
</tbody>
</table>
</div>
</body>
Here is my Angularjs
var bookApp = angular.module('bookApp', []);
bookApp.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('<(');
$interpolateProvider.endSymbol(')>');
});
bookApp.controller('bookListCtr', function ($scope, $http) {
$http.get('http://localhost/client_side/public/book').success(function(data) {
if(data.s_respond === 200){
$scope.items = data.data;
console.log(data.data)
}
});
});
This is Json data After console
s_respond = 200
data = "[{"id":"7","title":"Seven is my lucky number","link":"/api/v1/items/7"},{"id":"8","title":"A Dance with Dragons","link":"/api/v1/items/8"},{"id":"10","title":"Ten ways to a better mind","link":"/api/v1/items/10"},{"id":"42","title":"The Hitch-hikers Guide to the Galaxy","link":"/api/v1/items/42"},{"id":"200","title":"Book title #200","link":"/api/v1/items/200"},{"id":"201","title":"Book title #201","link":"/api/v1/items/201"},{"id":"202","title":"Book title #202","link":"/api/v1/items/202"},{"id":"203","title":"Book title #203","link":"/api/v1/items/203"},{"id":"204","title":"Book title #204","link":"/api/v1/items/204"},{"id":"205","title":"Book title #205","link":"/api/v1/items/205"}]"
I think that you need parse the json
$scope.items = JSON.parse(data.data);
a link that explain that:
https://www.quora.com/How-can-I-convert-JSON-format-string-into-a-real-object-in-JS
There r two tags... meaning 2 column try adding another in Ua body
<body ng-app="bookApp"> <div ng-controller="bookListCtr">
<table>
<thead>
<tr> <th>something</th> <th>something</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items"> <td>{{item.id }}</td>
<td>something else</td>
</tr>
</tbody>
</table>
</div>
</body>

Knockout list with jquery event

Why event does not occur on items when I am changing their values?
$(".target").change(function () {
alert($(".target").val());
});
function MyViewModel() {
var self = this;
self.items = ko.observableArray();
self.items.push({ name: 'Jhon' });
self.items.push({ name: 'Smith' });
}
ko.applyBindings(new MyViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<h2>Index</h2>
<table>
<thead>
<tr>
<th>Passenger name</th>
</tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td><input class="target" data-bind="value: name" /></td>
</tr>
</tbody>
</table>
Knockout generates new html upon applying foreach bindings, so you need to register your event globally, just like option 1 or you can do the neet binding of knockout just like in option 2.
I recommend option 2 to use knockout bindings.
$(document).on('change',".target",function () {
alert('option 1 - ' + $(this).val());
});
function MyViewModel() {
var self = this;
self.items = ko.observableArray();
self.items.push({ name: 'Jhon' });
self.items.push({ name: 'Smith' });
self.alert = function(data, e){
alert('option 2 - ' + data.name);
};
}
ko.applyBindings(new MyViewModel(), document.getElementById('tblSample'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<h2>Index</h2>
<table id="tblSample">
<thead>
<tr>
<th>Passenger name</th>
</tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td><input class="target" data-bind="value: name, event:{change:$parent.alert}" /></td>
</tr>
</tbody>
</table>

How to get the data from API and put into tha table (Jquery)

Trying to store all the information that getting from JSONP in the table.
Have done the test with 'alert' to make sure that there are more info that only one line and can see that there are more info that one.
But when run it, in the table I can see title row and first row.
Can somebody correct my error?
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js">
</script>
<script>
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.example.com/v1/deal/hotel?apikey=xxx&format=JSONP",
dataType : "jsonp",
success : function(parsed_json) {
$.each(parsed_json.Result, function( index, value ) {
alert( index + ": " + value.StarRating + " , "+ value.Url);
});
var from = parsed_json['Result'][0]['StartDate'];
document.getElementById("from").innerHTML = from;
var from = parsed_json['Result'][0]['StartDate'];
document.getElementById("from").innerHTML = from;
var to = parsed_json['Result'][0]['EndDate'];
document.getElementById("to").innerHTML = to;
var nights = parsed_json['Result'][0]['NightDuration'];
document.getElementById("nights").innerHTML = nights;
var currency = parsed_json['Result'][0]['CurrencyCode'];
document.getElementById("currency").innerHTML = currency;
var price = parsed_json['Result'][0]['Price'];
document.getElementById("price").innerHTML = price;
var link = parsed_json['Result'][0]['Url'];
document.getElementById("link").innerHTML = link;
//how to represent enlaces
var city = parsed_json['Result'][0]['City'];
document.getElementById("city").innerHTML = city;
var country = parsed_json['Result'][0]['CountryCode'];
document.getElementById("country").innerHTML = country;
var stars = parsed_json['Result'][0]['StarRating'];
document.getElementById("stars").innerHTML = stars;
}
});
});
</script>
</head>
<body>
<table id="t">
<tr>
<th>Start date</th>
<th>End date</th>
<th>Nights</th>
<th>Currency</th>
<th>Price</th>
<th>Link</th>
<th>City</th>
<th>Country Code</th>
<th>Star Rating</th>
</tr>
<tr>
<td id="from"></td>
<td id="to"></td>
<td id="nights"></td>
<td id="currency"></td>
<td id="price"></td>
<td id="link"></td>
<td id="city"></td>
<td id="country"></td>
<td id="stars"></td>
</tr>
</table>
</body>
</html>
The result of the Ajax callback is:
callback({"Errors":[],"Result":[{"FoundDate":"2013-12-04T16:11:36-08:00","CurrencyCode":"USD","NightDuration":"2.0","EndDate":"12/08/2013","Headline":"Cairo 5 Star Hotel, $36/night","IsWeekendStay":"true","Price":"36.0","StartDate":"12/06/2013","Url":"http‍://www.example.com/hotel/...&startDate=12/06/2013&endDate=12/08/2013&bid=0&sid=0","City":"Cairo","CountryCode":"EG","NeighborhoodLatitude":"30.0152","NeighborhoodLongitude":"31.1756","Neighborhood":"Cairo West - Giza","StarRating":"5.0","StateCode":"EG"},{"FoundDate":"2013-12-04T14:51:44-08:00",
If you have more than one line in result, then you have to -
Loop through it in the callback. You are not looping through it now. You are looping only for alert.
Dynamically create a new row in table for each line. You can clone the exiting tr for this using jquery clone method. But replace the id with 'class`.
Add data to that row pertaining to the line by modifying innerHtml of each td in the newly created row.
Finally, Append the row to the table
HTML -
<table id="t">
<tr>
<th>Start date</th>
<th>End date</th>
<th>Nights</th>
<th>Currency</th>
<th>Price</th>
<th>Link</th>
<th>City</th>
<th>Country Code</th>
<th>Star Rating</th>
</tr>
<tr class="first">
<td class="from"></td>
<td class="to"></td>
<td class="nights"></td>
<td class="currency"></td>
<td class="price"></td>
<td class="link"></td>
<td class="city"></td>
<td class="country"></td>
<td class="stars"></td>
</tr>
</table>
Javascript -
success : function(parsed_json) {
$.each(parsed_json.Result, function( index, record ) {
$row = $('.first').clone();
var from = record['StartDate'];
$row.find('.from').html(from);
//Similarly repeat the above two lines for other columns
//...
$('#t').append($row);
});
}

Categories