2016-05-06 35 views
0

我開發了一個AngularJS應用程序。AngularJS找不到數組中的值

在視圖中,我有一個項目列表 - 每個項目都有自己的一組單選按鈕。列表和按鈕是在API調用的運行時生成的。

列表和單選按鈕都可以是任意長度,例如列表項目1可能包含3個單選按鈕,而列表項目n可能包含2個單選按鈕。

當用戶選擇一個單選按鈕時,我會觸發一個ng-click方法,它將列表ID以及單選按鈕ID同時發送給控制器。

該視圖看起來如下,我已經測試了這一點,並將值發送到控制器。

<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> 

以我的doSomething()方法我試圖查看是否不checkItemDescription.fleetcheckitemidoption.fleetcheckid ID是一個現有的數組英寸

我使用indexOf()方法來比較值,但該方法似乎不工作 - 即使console.log()顯示值發送到控制器。

以下是我的doSomething()方法。

$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 
    } 
} 

我需要做的是創建一個帶有列表項ID,單選按鈕ID和一些其他值的JSON對象,例如,日期/時間根據用戶選擇發送到我的數據庫。

這是做到這一點的最佳方式還是有更好的方法?

回答

2

indexOf()方法返回可以在數組中找到給定元素的第一個索引,如果不存在給定元素,則返回-1。

-參照MDN

所以如果你的元素是第一個在集合中,那麼indexOf將返回0,這將導致執行else塊,所以改變你的if條件是這樣的。

if ($scope.initialFleetCheckIssueItemIDArray.indexOf(fleetCheckItemID) != -1) 
{ 
    //element found, do stuff here. 
} 
else 
{ 
    //element does not found, else stuff here. 
}