2013-05-29 39 views
0

我有一個使用ng-repeat重複使用的列表項。此列表項是關鍵詞建議的列表。我想使用jquery簡單地添加一個高亮CSS類,當用戶按下向上/向上箭頭,但我的jQuery不工作可能是因爲建議是由角插入。我如何讓jquery獲取當前DOM上的關鍵字建議,以便我的下一個和上一個工作?在重複列表項目中使用jquery next()prev()

HTML:

 <input type="text" placeholder="Destination" id="destination" data-ng-model="user_keyword" ui-event="{keyup: 'change($event, user_keyword)'}">  

     <ul> 
      <li data-ng-repeat="suggestion in suggestions"> 
      <a href="#" class="{{suggestion.highlight}}" data-ng-bind-html-unsafe="suggestion.place"></a> 
      </li> 
     </ul> 

javascipt的:

//Change is triggered every time a key is entered into input field 
$scope.change = function(e, term){ 

var result_id = 'destination'; 
var input = $('#'+'destination'); 
var result_container = $(result_id); 
var list_items = result_id+' li'; 
var selected_class = 'highlight'; 
var code = e.keyCode || e.which; 

    var $prev, $next, $current = $(list_items+'.'+selected_class); 
    var currentSelectedhtml; 

//key down press 
if (code === 40) { 

    $(list_items+":first").addClass(selected_class); 

    currentSelectedhtml = $(list_items+":first"); 

//key down or key right pressed 
} else if (code === 39 || code === 40) { 
    $next = $current.next("li"); 
    if ($next.length) { 
     $current.removeClass(selected_class); 
     $next.addClass(selected_class); 

     currentSelectedhtml = $next.html(); 
    } 

//key up or key left press 
} else if (code === 37 || code === 38) { 
    $prev = $current.prev("li"); 
    if ($prev.length) { 
     $current.removeClass(selected_class); 
     $prev.addClass(selected_class); 

     currentSelectedhtml = $prev.html(); 
    } 
} 

}; 

我還要補充一點,這個輸入字段是使用angularstrap可能有事情做的問題(不知道一個模式對話框內)。

總結我該如何讓jQuery獲取由angular創建的列表項?

在一個理想的情況下,我寧願只是使用角度,但我不能完全解決如何做到這一點看待next()和prev()是否需要,否則它看起來像我將不得不使用一些冗長的囉嗦for循環。

+0

你讀過:http://stackoverflow.com/a/15012542/45786 – TheHippo

回答

3

使角度越來越小,jQuery的方式就是使用angularJS的內置綁定和屬性。 Here is a concept plunk通過單擊按鈕訪問和更改ng-repeat中的項目類別。

這普拉克利用了:

  1. ng-class其用於有條件地設置類的元素的。
  2. $index它可以方便地訪問ng-repeat中元素的索引。

這些概念很好地解釋了here (conditional styles)here (ng-class)

在標記:

<div ng-repeat="item in myItems" ng-class="{'selected': $index == selectedIndex}"> 
    <div >{{item}}</div> 
</div> 

<button ng-click="change()">Change</button> 

,並在控制器:

$scope.selectedIndex = 0; 
    $scope.change = function(){ 
     console.log($scope.selected); 
     var last_item = $scope.myItems.length - 1; 
     if ($scope.selectedIndex == last_item){ 
      $scope.selectedIndex = 0; 
     } else { 
      $scope.selectedIndex += 1; 
      } 
     } 
+1

謝謝你這個工作。我會在上面做更多的閱讀。 – Malcr001

+0

我認爲從長遠來看,角度上的全押是更少的工作和更容易維護的代碼。缺點是你沒有得到許多使jQuery如此簡單和流行的方便包裝。 – rGil