2015-09-01 92 views
0

我在我的HTML頁面中有一段代碼,帶有一個非常標準的控制器。AngularJS複選框點擊輸入字段

<table class="table table-striped"> 
    <tr> 
     <th>Item ID</th> 
     <th>1st Value</th> 
     <th>2nd Value</th> 
    </tr> 
    <tr ng-repeat="(id, values) in myItemList"> 
     <td> <input type="checkbox" ng-model="selected[id]"> {{id}}</td> 
     <td> <input type="number" ng-model="values.first"></td> 
     <td> <input type="number" ng-model="values.second"></td> 
    </tr> 
</table> 

在上面的代碼中,只有在單擊複選框時纔會選擇一個項目。但是,我希望當用戶點擊任何特定行的兩個數字輸入字段中的任何一個時,都會檢查相關的複選框。

我還沒有找到任何類似的問題。通常,開發人員面臨的問題是在選中複選框時發生某些事情。但是,這種情況是不同的。

我不知道如何AngularJS可以幫助我解決這個問題,考慮到行通過ng-repeat循環顯示。任何建議?

回答

1

可以實現這樣說:

HTML:

<div ng-app="testApp"> 
<div ng-controller="testController"> 
    <table class="table table-striped"> 
     <tr> 
      <th>Item ID</th> 
      <th>1st Value</th> 
      <th>2nd Value</th> 
     </tr> 
     <tr ng-repeat="(id, values) in myItemList"> 
      <td> <input type="checkbox" ng-model="selected[id]"> {{id}}</td> 
      <td> <input type="number" ng-click="selectRow(id);" ng-model="values.first"></td> 
      <td> <input type="number" ng-click="selectRow(id);" ng-model="values.second"></td> 
     </tr> 
    </table> 
</div> 

控制器代碼:

var app = angular.module('testApp', []); 
app.controller('testController', function ($scope) { 
    $scope.myItemList = [{ first: 'aaa', second: 'bbbb' }, { first: 'aa1', second: 'bbb1' }, { first: 'aa2', second: 'bbb2' }]; 
    $scope.selected = [false, false, false]; 
    $scope.selectRow = function (id) { 
     $scope.selected[id] = true; 
    } 
}); 

的jsfiddle:https://jsfiddle.net/ffxddsre/

正如您所看到的,我所做的只是添加一個selectRow函數並將其綁定到輸入的click事件,當單擊輸入時它將設置相應的選定標誌,並且Angular的雙向綁定機制負責更新UI。

+0

當然,我怎麼不想這個呢?非常簡單和乾淨的解決方案,謝謝! – user1472709

相關問題