Reputation: 1895
I am trying to change a boolean value when a user clicks on a table row that is populated with JSON. For example I have this...
$scope.prices = {
"Prices": [
{
"Code": "edl",
"Selected": false
},
{
"Code": "ead",
"Selected": false
}
]
}
Which I then bind to a table...
<table>
<tr ng-click="change(item.code)" ng-repeat="item in prices">
<td>{{prices.Code}}</td>
</tr>
</table>
And when a user clicks on a row the change function is fired that would then change the selected value to either true or false
$scope.change = function (itemCode) {
//update the clicked code selcted value to True/False
// first check if its true or false
// then change it accordingly
// Please excuse my terrible attempt!
if(!$scope.prices.code.selected){
$scope.prices.code.selected = true
} else {
$scope.prices.code.selected = false
}
};
As I'm not sure how to achieve this from the change function. Or is there another way? Thanks
Upvotes: 1
Views: 1868
Reputation: 8325
Here is another cleaner solution without involving functions, this approach will release you from removing functions from $scope if you are cautious of memory usage.
<table>
<tr ng-click="item.Selected = !item.Selected" ng-repeat="item in prices">
<td>{{item.Code}}</td>
</tr>
</table>
Happy Helping!
Upvotes: 0
Reputation: 909
First a few corrections.
Refer to the array Prices
inside $scope.prices
.
Change the signature of the change()
so that it gets the reference to the item that was clicked.
<table>
<tr ng-click="change(item)" ng-repeat="item in prices.Prices">
<td>{{item.Code}}</td>
</tr>
</table>
Now implement the change method
$scope.change = function (item) {
if (item.Selected) {
item.Selected = false;
} else {
item.Selected = true;
}
};
Upvotes: 1
Reputation: 38131
First of all, it doesn't make much sense to have an extra level in $scope.prices
before you get to the actual array of prices.
In other words, instead of having:
$scope.prices = {
"Prices": [
{
"Code": "edl",
"Selected": false
},
// etc.
]
};
You should just have the array straight up, so you can bind to it easily:
$scope.prices = [
{
"Code": "edl",
"Selected": false
},
// etc
];
Then you can bind to it like so:
<table>
<tr ng-click="change(item)" ng-repeat="item in prices">
<td>{{item.Code}}</td>
</tr>
</table>
Finally, now that $scope.change()
gets the whole item, instead of just the code, you can toggle its Selected
property directly:
$scope.change = function (item) {
item.Selected = !item.Selected;
};
Upvotes: 2