在ng-repeat AngularJS中使用ICheck单选按钮获取所选索引

时间:2016-11-15 03:18:50

标签: jquery angularjs icheck

<tr ng-repeat="school in schools">
 <td>{{school.Location}}</td>
 <td>{{school.Type}}</td>
 <td>{{school.Name}}</td>
 <td class="school-action text-center">
     <label>                             
           <input type="radio" name="masdoc-school" class="flat-red" />
     </label>
 </td>
</tr>

我已经定义了Icheck

$('input[type="radio"].flat-red').iCheck({
    checkboxClass: 'icheckbox_square-blue',
    radioClass: 'iradio_square-blue'
});

$ scope.schools是一个数组对象,我如何获得输入的选择索引[name =&#34; masdoc-school&#34;]以获得控制器中$ scope.schools [selected index]的值。谢谢大家!

1 个答案:

答案 0 :(得分:1)

问题解决!在https://github.com/fronteed/icheck/issues/62

使用(wajatimur)的icheck指令
app.directive('icheck', function($timeout, $parse) {
    return {
        require: 'ngModel',
        link: function($scope, element, $attrs, ngModel) {
            return $timeout(function() {
                var value;
                value = $attrs['value'];

                $scope.$watch($attrs['ngModel'], function(newValue) {
                    $(element).iCheck('update');
                })

                return $(element).iCheck({
                    checkboxClass: 'icheckbox_square-blue',
                    radioClass: 'iradio_square-blue'

                }).on('ifChanged', function(event) {
                    if ($(element).attr('type') === 'checkbox' && $attrs['ngModel']) {
                        $scope.$apply(function() {
                            return ngModel.$setViewValue(event.target.checked);
                        });
                    }
                    if ($(element).attr('type') === 'radio' && $attrs['ngModel']) {
                        return $scope.$apply(function() {
                            return ngModel.$setViewValue(value);
                        });
                    }
                });
            });
        }
    };
});

然后在ng-repeat中:

<tbody>
   <tr ng-repeat="school in schools">
       <td>{{school.Location}}</td>
       <td>{{school.Type}}</td>
       <td>{{school.Name}}</td>
       <td class="school-action text-center">
          <label>
               <input icheck type="radio" name="iCheck" class="flat-red" ng-value={{$index}} ng-model="$parent.schoolIndex" ng-change="changeFaculty(schoolIndex)"/>
          </label>
       </td>
   </tr>

在ng-model中使用$ parent,因为ngRepeat将为其子项创建新范围(以及原型继承如何影响范围),因此ng-change只会触发事件一次。