Add item to array Angular - javascript

I have a table with these fields: product, lot, input1, input2. You can clone a line, and you can add a new line.
What I want to do is that for each row you can add a new Lot created by a "number" and by "id" that user write in the input field under the Select lot. And I wanted that the script add the new Lot in the json data and the lot 's option list.
This is the function for add that I tried to do:
$scope.addLot = function() {
var inWhichProduct = row.selectedProduct;
var newArray = {
"number": row.newLot.value,
"id": row.newLot.id
};
for (var i = 0; i < $scope.items.length; i++) {
if ($scope.items[i].selectedProduct === inWhichProduct) {
$scope.items[i].selectedLot.push(newArray);
}
}
};
-->> THIS <<-- is the full code.
Can you help me?

I think your question is a little too broad to answer on Stack Overflow, but here's an attempt:
<div ng-app="myApp" ng-controller="myCtrl">
<table>
<tr ng-repeat="lot in lots">
<td>{{ lot.id }}</td>
<td>{{ lot.name }}</td>
</tr>
</table>
<p>name:</p> <input type="text" ng-model="inputName">
<p>id:</p> <input type="text" ng-model="inputId">
<button ng-click="addLotButton(inputId, inputName)">Add</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.lots = [{
name: "test",
id: 1
},
{
name: "test2",
id: 2
}
];
$scope.addLot = function(lotId, lotName) {
var newLotObject = {
name: lotName,
id: lotId
};
$scope.lots.push(newLotObject);
};
$scope.addLotButton = function(id, name) {
$scope.addLot(id, name);
};
$scope.addLot(3, "Another test");
});
</script>
Basically this code just takes some input and adds an object to the scope for that input. The table is created using an ng-repeat of this data. It's not great code at all but it's just a quick example.

The push method adds newArray to selectedLot array. It's not working on the JSON data but on arrays. If you want to have the JSON, you can give a try to :
var myJsonString = JSON.stringify(yourArray);
It will create a JSON string based on the parameter
Maybe you should try to structure your data to make lots as properties of products.
{
products: [
{id: 1, lots: [{id:1}, {id:2}]},
{id: 2, lots: [{id:1}, {id:2}]}
]
}
To add a lot to a product :
product = products[0];
product.lots.push(newArray);

Change the fallowing:
html:
<button ng-click="addLot(row.selectedProduct.id,row.newLot.value,row.newLot.id)">Add</button>
js:
$scope.addLot = function(id,val,lotId) {
// console.log(id);
var inWhichProduct = id;
var newArray = { "value": val, "id": lotId };
//console.log($scope.items)
angular.forEach($scope.items,function(v,i){
if($scope.items[i].id == id )
{
$scope.items[i].lots.push(newArray);
console.log($scope.items[i].lots);
}
});
};
http://plnkr.co/edit/W8eche8eIEUuDBsRpLse?p=preview

Related

Angular js solve a different format of a json array of objects

Based on the result below , how can an angular for each loop be able to solve that json array of objects format ? The value is title and the id is key. Any Idea? Thank you.
mycode
me.record.questionaires = []
angular.forEach(detail.questionaires, function (value, key) {
me.record.questionaires.push({ "id": key, "title": value })
});
Formated json data (detail.questionaire result)
[
"{'sub_title': 'dsadsa', 'instruction': 'You Must',…elimit': '01:05:19', 'title': 'asdsa', 'id': 133}",
"{'sub_title': 'sdasdsa', 'instruction': None, 'cre…melimit': '05:30:09', 'title': 'asda', 'id': 131}"
]
You need to
Loop over the array
Parse the string as JSON
Push or map the appropriate values into your questionaires array (it's not clear what data you want)
me.record.questionaires = detail.questionaires.map(json => {
let { id, title } = JSON.parse(json)
return { id, title }
})
I had to change your sample formatted JSON a bit because it was giving me console errors. Please see if this helps.
angular
.module("myModule", [])
.controller("myController", function($scope) {
var me ={record: {questionaires: []}};
$scope.me = me;
var detail ={};
detail.questionaires = [
"{'sub_title': 'dsadsa', 'instruction': 'You Must','…elimit': '01:05:19', 'title': 'asdsa', id: 133}",
'{"sub_title": "sdasdsa", "instruction": "None", "cre…melimit": "05:30:09", "title": "asda", "id": 131}'
];
angular.forEach(detail.questionaires, function (value, key) {
var questionaire = JSON.parse(value.replace(/'/g, '"').replace(/id:/g, '"id":'));
me.record.questionaires.push({ "id": questionaire.id, "title": questionaire.title });
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myModule">
<div ng-controller="myController">
<div><strong>me.record.questionaires:</strong></div>
<div ng-repeat="q in me.record.questionaires">
<div>{{q}}</div>
</div>
</div>
</div>

How to avoid multiple map functionality

I have two objects. First one have entire school full details of students record. Example like
var first = {
students:
[
{ id:'1', name:"suresh", age:"20", degree:"BSc", status:"obsent"},
{ id:'2', name:"ramesh", age:"21", degree:"BCom", status:"present"},
{ id:'3', name:"rajesh", age:"19", degree:"BA", status:"leave"},
{ id:'4', name:"satish", age:"28", degree:"BL", status:"obsent"}
]
}
Second one have particular class students information about the status of the student for that day. Example like
var second ={
students:
[
{ id:'1',status:"present"},
{ id:'12',status:"obsent"},
{ id:'3',status:"obsent"},
{ id:'14',status:"leave"}
]
}
Now I need to compare the student id and need to display the status based on the result. I have achieved in the following way.
items = first.students.map(function(item){
status =item.status;
second.students.map(function(key){
if(key.id == item.id) { status = key.status }
});
return "<tr><td>"+item.name+"</td><td>"+item.age+"</td><td>"+item.degree+"</td><td>"+status+"</td></tr>";
});
$('table#main tbody').html(items);
The above code is working fine. But if you look at my code, I have used the map functionality multiple times. I feel that I have done something wrong in the performance wise. Is that possible to reduce using the map twice or any other better way to achieve the same result. Please suggest me.
Code Snippet
var first = {
students:
[
{ id:'1', name:"suresh", age:"20", degree:"BSc", status:"obsent"},
{ id:'2', name:"ramesh", age:"21", degree:"BCom", status:"present"},
{ id:'3', name:"rajesh", age:"19", degree:"BA", status:"leave"},
{ id:'4', name:"satish", age:"28", degree:"BL", status:"obsent"}
]
}
var second ={
students:
[
{ id:'1',status:"present"},
{ id:'12',status:"obsent"},
{ id:'3',status:"obsent"},
{ id:'14',status:"leave"}
]
}
items = first.students.map(function(item){
status =item.status;
second.students.map(function(key){
if(key.id == item.id) { status = key.status }
});
return "<tr><td>"+item.name+"</td><td>"+item.age+"</td><td>"+item.degree+"</td><td>"+status+"</td></tr>";
});
$('table#main tbody').html(items);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="main" cellspacing="2" border="1">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Degree</th>
<th>Stauts</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</tbody>
</table>
Due to the way your objects are set up, it looks like that will be O(n) time for the lookup, because you need to loop through the first student array for every student id.
To get around this, you can do a single map where you assign the id as the key of a new intermediate object in the format of:
x = {1: {...}, 2: {...}}
From there, you can now do constant time O(1) lookups:
x[id]
The only extra work is building the intermediate hash, but that will be less computation than what you have above.
See this example below. Note that it does use 2 maps, but it's different than your example because it's not a map within a map which is exponential:
var students = [
{ id:'1', name:"suresh", age:"20", degree:"BSc", status:"obsent"},
{ id:'2', name:"ramesh", age:"21", degree:"BCom", status:"present"},
{ id:'3', name:"rajesh", age:"19", degree:"BA", status:"leave"},
{ id:'4', name:"satish", age:"28", degree:"BL", status:"obsent"}
];
var studentIds = {};
students.forEach(function(student) {
studentIds[student.id] = {name: student.name, age: student.age, degree: student.degree, status: student.status}
});
var second = [
{ id:'1',status:"present"},
{ id:'12',status:"obsent"},
{ id:'3',status:"obsent"},
{ id:'14',status:"leave"}
];
var studentStatuses = second.map(function(student) {
// do whatever you have to do here
return (studentIds[student.id] || {}).status;
});
The complexity will be better if you build an object which keys are id and values are status from second.students then you update status in first.students based on this object:
var first = {
students:
[
{ id:'1', name:"suresh", age:"20", degree:"BSc", status:"obsent"},
{ id:'2', name:"ramesh", age:"21", degree:"BCom", status:"present"},
{ id:'3', name:"rajesh", age:"19", degree:"BA", status:"leave"},
{ id:'4', name:"satish", age:"28", degree:"BL", status:"obsent"}
]
}
var second ={
students:
[
{ id:'1',status:"present"},
{ id:'12',status:"obsent"},
{ id:'3',status:"obsent"},
{ id:'14',status:"leave"}
]
}
var statusById= second.students.reduce(function(m, e) {
m[e.id] = e.status;
return m;
}, {});
items = first.students.map(function(item){
item.status = statusById[item.id] || item.status;
return "<tr><td>"+item.name+"</td><td>"+item.age+"</td><td>"+item.degree+"</td><td>"+item.status+"</td></tr>";
});
$('table#main tbody').html(items);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="main" cellspacing="2" border="1">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Degree</th>
<th>Stauts</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</tbody>
</table>

Filtering complex object inside nested ng-repeat

I want to filter object inside nested ng-repeat.
HTML:
<div ng-controller="MyController">
<input type="text" ng-model="selectedCityId" />
<ul>
<li ng-repeat="shop in shops">
<p ng-repeat = "locations in shop.locations | filter:search" style="display: block">
City id: {{ locations.city_id }}
<span style="padding-left: 20px; display: block;" ng-repeat="detail in locations.details | filter:item">Pin code: {{detail.pin}}</span>
</p>
</li>
</ul>
Controller:
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function ($scope) {
$scope.search = function (location) {
if ($scope.selectedCityId === undefined || $scope.selectedCityId.length === 0) {
return true;
}
if (location.city_id === parseInt($scope.selectedCityId)) {
return true;
}
};
$scope.item = function (detail) {
if ($scope.selectedCityId === undefined || $scope.selectedCityId.length === 0) {
return true;
}
if (detail.pin == parseInt($scope.selectedCityId)) {
return true;
}
};
$scope.shops =
[
{
"category_id":2,
"locations":[
{
"city_id":368,
"details": [{
"pin": 627718,
"state": 'MH'
}]
}
]
},
{
"name":"xxx",
"category_id":1,
"locations":[
{
"city_id":400,
"region_id":4,
"details": [{
"pin": 627009,
"state": 'MH'
},{
"pin": 129818,
"state": 'QA'
}]
},
]
},
];
});
Here's the fiddle:
http://jsfiddle.net/suCWn/210/
I want to use multiple filter inside ng-repeat.
Example: Whenever user enters the ID in the input box. The list should filter based on cityID or PinCode.
if user enter '129818' it should show pin code result of 129818 along with its parent cityID
Similarly, if a user enter 400, the list should filter and show cityID result with 400 along with its child pin code.
EDIT:
Update Code http://codepen.io/chiragshah_mb/pen/aZorMe?editors=1010]
First, you must not filter locations with matching details. Use something like this in the search filter:
$scope.search = function (location) {
var id = parseInt($scope.selectedCityId);
return isNaN(id) || location.city_id === id ||
location.details.some(function(d) { return d.pin === id });
};
To show details if filtered by cityID, you have to find the parent location and check if it was filtered.
$scope.item = function (detail) {
var id = parseInt($scope.selectedCityId);
return isNaN(id) || detail.pin === id || locationMatches(detail, id);
};
function locationMatches(detail, id) {
var location = locationByDetail(detail);
return location && location.city_id === id;
}
function locationByDetail(detail) {
var shops = $scope.shops;
for(var iS = 0, eS = shops.length; iS != eS; iS++) {
for(var iL = 0, eL = shops[iS].locations.length; iL != eL; iL++) {
if (shops[iS].locations[iL].details.indexOf(detail) >= 0) {
return shops[iS].locations[iL];
}
}
}
}
EDIT Another, more flexible solution would be to remove all the filters from ngRepeats and do the filtering in a method that you call on ngChange of the search text. Here is the basic structure for this approach.
myApp.controller('MyController', function($scope, $http) {
var defaultMenu = [];
$scope.currentMenu = [];
$scope.searchText = '';
$http.get(/*...*/).then(function (menu) { defaultMenu = menu; } );
$scope.onSearch = function() {
if (!$scope.searchText) {
$scope.currentMenu = defaultMenu ;
}
else {
// do your special filter logic here...
}
};
});
And the template:
<input type="text" ng-model="searchText" ng-change="onSearch()" />
<ul>
<li ng-repeat="category in currentMenu">
...
</li>
</ul>
I have updated your filters. The problem is in your search filter you are only checking for the city_id, what you should do is:
Check if the typed id is city_id
Check if typed id is a pid of a child detail of given location
Similar thing for the item filter:
Check if the typed id is a pid of the detail being filtered
Check if the typed id is a city_id of the parent location of the detail passed in
Here is a working jsFiddle. I hope this helps.
By simply modifying the JSON to include the city_id for children so you don't need to loop through it to get the parent's city_id, the solution is as easy as this:
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function ($scope) {
$scope.search = function (location) {
if (!$scope.selectedCityId)
return true;
//if user's input is contained within a city's id
if (location.city_id.toString().indexOf($scope.selectedCityId) > -1)
return true;
for (var i = 0; i < location.details.length; i++)
//if user's input is contained within a city's pin
if (location.details[i].pin.toString().indexOf($scope.selectedCityId) > -1)
return true;
};
$scope.item = function (detail) {
if (!$scope.selectedCityId)
return true;
//if user's input is contained within a city's id
if (detail.city_id.toString().indexOf($scope.selectedCityId) > -1)
return true;
//if user's input is contained within a city's pin
if (detail.pin.toString().indexOf($scope.selectedCityId) > -1)
return true;
};
Modified JSON
$scope.shops=[{"category_id":2,"locations":[{"city_id":368,"details":[{"city_id":368,"pin":627718,"state":'MH'}]}]},{"name":"xxx","category_id":1,"locations":[{"city_id":400,"region_id":4,"details":[{"city_id":400,"pin":627009,"state":'MH'},{"city_id":400,"pin":129818,"state":'QA'}]},]},];});
If directly modifying the JSON is not possible, you can modify it like this in this controller directly after this $scope.shops = ...json... statement:
for(var i=0; i<$scope.shops.length; i++)
for(var j=0, cat=$scope.shops[i]; j<cat.locations.length; j++)
for(var k=0, loc=cat.locations[j]; k<loc.details.length; k++)
loc.details[k].city_id=loc.city_id;
Working fiddle:
http://jsfiddle.net/87e314a0/
I tried to make the solution easier to understand :
index.html :
<div ng-controller="MyController">
<input type="text" ng-model="search.city_id" />
<ul>
<li ng-repeat="shop in shops">
<p ng-repeat = "locations in shop.locations | filter:search.city_id" style="display: block">
City id: {{ locations.city_id }}
<span style="padding-left: 20px; display: block;" ng-repeat="detail in locations.details | filter:item">Pin code: {{detail.pin}}</span>
</p>
</li>
</ul>
</div>
app.js :
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function ($scope) {
$scope.shops =
[
{
"category_id":2,
"locations":[
{
"city_id":368,
"details": [{
"pin": 627718,
"state": 'MH'
}]
}
]
},
{
"name":"xxx",
"category_id":1,
"locations":[
{
"city_id":400,
"region_id":4,
"details": [{
"pin": 627009,
"state": 'MH'
},{
"pin": 129818,
"state": 'QA'
}]
},
]
},
];
});
Here's the fiddle :
mySolution

Insert a new inner object into array of objects observable array and update the DOM

HTML with bindings:
<div class="container" data-bind="foreach: { data: Conferences, as: 'conf' }">
<div class="conf" data-bind="attr: { id : conf.Id }">
<div class="conf-month" data-bind="text: conf.StartTime"></div>
<div class="conf-day" data-bind="text: conf.EndTime"></div>
<div class="add-user">
<input type="tel" data-bind="value: $root.PhoneNumber />
<input type="email" data-bind="value: $root.Email" />
<a id="add-user" title="Add new user" data-bind="attr: { value: conf.Id }, click: $root.addUserToConference">Add</a>
</div>
<div class="conf-users" data-bind="foreach: { data: conf.ConferenceUsers, as: 'user' }">
<div class="conf-user" data-bind="attr: { id: 'confuser-' + user.Id}">
<span data-bind="text: user.Name"></span>
<span data-bind="text: user.PhoneNumber"></span>
<span data-bind="text: user.Email"></span>
</div>
</div>
</div>
</div>
KnockoutJs ViewModel:
function ConferenceViewModel() {
var self = this;
self.Conferences = ko.observableArray([]);
self.PhoneNumber = ko.observable("");
self.Email = ko.observable("");
self.getAllConfs = function () {
$.ajax({
type: 'GET',
url: '/confs/getconfs',
}).done(function (confs) {
$.each(confs, function (index, conf) {
//populate the list on document ready
confVm.Conferences.push(conf);
};
}).fail(showError);
}
self.addUserToConference = function (viewModel, event) {
var user = {
"Id": 0,
"ConferenceId": viewModel.Id(),
"Email": "self.Email()",
"PhoneNumber": self.PhoneNumber(),
};
// here we should insert a new ConferenceUser into the Conferences observable array
// and also update the DOM
// ajax to insert user to db
}
After I populate the above Conferences observableArray via ajax,
the output of console.log(ko.toJSON(confVm.Conferences())) is as follows:
[
{
"ConferenceUsers":[
{
"Id":3006,
"ConferenceId":8,
"Name":null,
"Email":"mail#lala.com",
"UserName":null,
"PhoneNumber":"234234234234",
"ChannelId":null,
"State":null,
"Type":null,
"RecordingId":null
}
],
"Id":8,
"Subject":"YYYhaaaaa",
"StartTime":"2016-05-29T18:30:00",
"EndTime":"2016-05-29T19:30:00",
"OrganizerEmail":"elpas#live.com",
"OrganizerName":"dasdasd",
"Pin":"6402",
"BridgeId":null,
"State":null
},
{
"ConferenceUsers":[
{
"Id":3013,
"ConferenceId":12,
"Name":null,
"Email":"dsfdfsdfdsf#dfdfdf.com",
"UserName":null,
"PhoneNumber":null,
"ChannelId":null,
"State":null,
"Type":null,
"RecordingId":null
}
],
"Id":12,
"Subject":"dsfsdfdsfsdf",
"StartTime":"2016-05-31T22:00:00",
"EndTime":"2016-05-31T23:00:00",
"OrganizerEmail":"d#adssad.com",
"OrganizerName":"dsfdsfsdf",
"Pin":"3402",
"BridgeId":null,
"State":null
}
]
Q: How can I insert a new ConferenceUser by ConferenceId and update the DOM accordingly?
You'll need to execute four steps:
Get the current list of conferences from the observable array Conferences
Find the conference with the right id
Push a new user to this conference's ConferenceUsers
Make sure Conferences is set with the new data
While all steps are pretty straight forward to execute, there'll be some drawbacks to how they'd work:
The Conference objects and the ConferenceUsers arrays aren't observable. Knockout isn't automatically aware of any changes inside the Conference objects. So, after step 3 and 4, to knockout, it won't appear as if anything's changed: the Conferences array still has the same objects in it.
My advice:
If adding new users to conferences is something that will happen regularly, I'd suggest creating a Conference viewmodel that has a ko.observableArray of users. Alternatively, you could create new Conference objects for every minor change, which will trigger knockout to re-render the entire UI instead of just the relevant part (assuming you've used a foreach data-bind somewhere).
A quick example of how you could map your regular Conference objects to viewmodels:
// Your JSON data from the ajax request (an array of objects)
var conferencesData = [];
var Conference = function(conferenceJSON) {
// It's better to map all properties you're using individually,
// but this at least exposes the original JSON object
this.props = conferenceJSON;
this.users = ko.observableArray(conferenceJSON.conferenceUsers);
};
var createConference = function(conferenceJSON) {
return new Conference(conferenceJSON);
};
var ConferenceList = function(conferencesJSON) {
var self = this;
this.conferences = ko.observableArray(conferencesJSON.map(createConference));
this.addConference = function(conferenceJSON) {
self.conferences.push(createConference(conferenceJSON));
};
this.addUserToConference = function(userJSON) {
var conferences = self.conferences();
for (var c = 0; c < conferences.length; c += 1) {
// Step 2: Find the conference with the required id
if (conferences[c].props.id === userJSON.ConferenceId) {
// Step 3: We're pushing to an observableArray, so no need
// to worry about Step 4.
conferences[c].users.push(userJSON);
return true;
}
}
return false;
};
};
ko.applyBindings(new ConferenceList(conferencesData));
Try this:
var obj = [
{
"ConferenceUsers":[
{
"Id":3006,
"ConferenceId":8,
"Name":null,
"Email":"mail#lala.com",
"UserName":null,
"PhoneNumber":"234234234234",
"ChannelId":null,
"State":null,
"Type":null,
"RecordingId":null
}
],
"Id":8,
"Subject":"YYYhaaaaa",
"StartTime":"2016-05-29T18:30:00",
"EndTime":"2016-05-29T19:30:00",
"OrganizerEmail":"elpas#live.com",
"OrganizerName":"dasdasd",
"Pin":"6402",
"BridgeId":null,
"State":null
},
{
"ConferenceUsers":[
{
"Id":3013,
"ConferenceId":12,
"Name":null,
"Email":"dsfdfsdfdsf#dfdfdf.com",
"UserName":null,
"PhoneNumber":null,
"ChannelId":null,
"State":null,
"Type":null,
"RecordingId":null
}
],
"Id":12,
"Subject":"dsfsdfdsfsdf",
"StartTime":"2016-05-31T22:00:00",
"EndTime":"2016-05-31T23:00:00",
"OrganizerEmail":"d#adssad.com",
"OrganizerName":"dsfdsfsdf",
"Pin":"3402",
"BridgeId":null,
"State":null
}
];
/* Iterate all conferences */
for (var i in obj) {
/* Find conference with ID = 8 */
if (obj[i].Id === 8) {
/* Add a new user to the conference */
obj[i].ConferenceUsers.push({
"Id":1111,
"ConferenceId":1,
"Name":null,
"Email":"test#example.com",
"UserName":null,
"PhoneNumber":null,
"ChannelId":null,
"State":null,
"Type":null,
"RecordingId":null
});
break;
}
}
console.log(obj); // output result

Assign ng-model to checkbox if some value == anothervalue

I have a User object in Angular controller. I also have an array of Account objects with respective ID for each.
In User I have a field "default_account" where I want to put ID of a default account. So, user can have a lot of accounts but only one of them can be default. When I go to Account options, I have a checkbox there which is responsible for setting/unsetting the account as default.
Now I want to set checkbox on/off depending on its being default for the user. And I also need to respectively change default_account field inside User object on checkbox change. It puzzles me quite much how I can do it.
Any advice is appreciated!
Very approximate (didn't text that):
html:
<div ng-repeat="account in accounts">
<input type="checkbox" ng-checked="account == user.default_acount"
ng-click="SelectAssDefault(account )" />
</div>
js:
function MyCtrl($scope) {
$scope.user = { name: 'user', default_acount: null};
$scope.accounts = [{ }, { }, ...];
$scope.SelectAssDefault = function (account) {
$scope.user.default_acount = account;
};
}
EDIT: a working example: http://jsfiddle.net/ev62U/120/
If you want to set a checkbox to true based on a variable, you can set ng-checked="variable" within the input tag.
If the variable is true the box will be checked. If it's false it won't. Alternatively, an expression will also work e.g. ng-checked="1===1" will evaluate to true.
If you want to alter something else based on user clicking on the checkbox, set ng-click="someCtrlFunction()" within the input tag. This will call a function in your controller. You can look up the value of the checkbox from your controller if you've bound to it.
Here's a fiddle: http://jsfiddle.net/E8LBV/10/ and here's the code:
HTML
<div ng-app="App">
<div ng-controller="AppCtrl">
<ul>
<li ng-repeat="user in users">{{user.name}}
<ul>
<li ng-repeat="account in user.accounts">
<input type="checkbox" ng-model="checked" ng-checked="account == user.default" ng-click="changeDefault(user.id,account,checked)">{{account}}</input>
</li>
<ul/>
</li>
</ul>
</div>
</div>
JS
var app = angular.module('App', []);
app.service('Users', function () {
var Users = {};
Users.data = [{
'id': 1,
'name': 'jon',
'default': null
}, {
'id': 2,
'name': 'pete',
'default': null
}];
return Users;
});
app.service('Accounts', function () {
var Accounts = {};
Accounts.data = [{
'user': 1,
'ac': 123456
}, {
'user': 2,
'ac': 456832
}, {
'user': 2,
'ac': 345632
}, {
'user': 1,
'ac': 677456
}];
return Accounts;
});
app.controller('AppCtrl', function ($scope, Users, Accounts) {
$scope.users = Users.data;
//attach accounts to user
for (i = 0; i < $scope.users.length; i++) {
$scope.users[i].accounts = [];
for (ii = 0; ii < Accounts.data.length; ii++) {
if (Accounts.data[ii].user == $scope.users[i].id) {
$scope.users[i].accounts.push(Accounts.data[ii].ac);
}
}
}
//function to change the default account for the user
$scope.changeDefault = function (id, account, checked) {
if (!checked) {
return;
}
for (i = 0; i < $scope.users.length; i++) {
if ($scope.users[i].id == id) {
$scope.users[i].
default = account;
}
}
}
});
Here is my solution that perfectly worked for me!
<tbody ng-repeat="account in accounts">
<tr>
<td ><a ng-click="getloandetails(account.idAccount)">{{account.accountName}}</a></td>
<td>$ {{account.currentBalance}}</td>
</tr>
</tbody>
and in Angular side just do this:
$scope.getloandetails = function(accountId) {
alert('Gettring details for the accountId: ' + accountId);
};

Categories

Resources