Reputation: 2051
I have a AngularJS app developed.
On a view I have a list of items - each with its own set of radio buttons. The list and buttons are built at run-time from an API call.
Both the list and radio buttons can be of any length e.g. list item 1 might contain 3 radio buttons while list item n might contain 2 radio buttons.
When the user selects a radio button I fire a ng-click method that sends both the list ID as well as the radio button ID to the controller.
The view looks as follows and I have tested this and the values are being sent to the controller.
<label class="radio-button" ng-repeat="option in checkItemDescription.options">
<input type="radio" name="option_question_id_{{checkItemDescription.fleetcheckitemid}}"
ng-model="checkItemDescription.selected_id"
ng-click="doSomething(checkItemDescription.fleetcheckitemid, option.fleetcheckid)"
ng-value="option.fleetcheckid">
<div class="radio-button__checkmark"></div>
Description: {{option.checkvaluedesc}}
</label>
In my doSomething() method i am trying to see if either the checkItemDescription.fleetcheckitemid or the option.fleetcheckid id is in a existing array.
I use indexOf() method to compare the values but the method does not seem to work - even though console.log() shows values are sent to the controller.
Below is my doSomething() method.
$scope.doSomething = function(fleetCheckItemID, fleetCheckID)
{
if ( $scope.initialFleetCheckIssueItemIDArray.indexOf(fleetCheckItemID))
{
console.log("Yeah!"); // Never gets to here even though logs show values exist
}
else
{
console.log("Ah!"); // Always get here
}
}
What I need to do is to to create a JSON object with the list item ID, radio button ID and some other values e.g. date/time based on the user selection to send to my Database.
Is this the best way to do it or is there a better way?
Upvotes: 0
Views: 43
Reputation: 6766
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
-referenced from MDN.
so if your element is first in the collection then indexOf would return 0 which would result in the execution of else block so change your if condition like this.
if ( $scope.initialFleetCheckIssueItemIDArray.indexOf(fleetCheckItemID) != -1 )
{
//element found, do stuff here.
}
else
{
//element does not found, else stuff here.
}
Upvotes: 2