Encapsulate the iCheck plug-in into components in the form of angularjs

In the recent angularjs project, if you want to make multi selection and radio box more beautiful, you have referenced the iCheck plug-in in the project.
However, after using the icheck plug-in, a beautified div will be generated to cover the original checkbox or radio, and the original checkbox or radio will be hidden.
Therefore, when clicking the multi selection box, the event will not be triggered directly to change the model value bound to the checkbox or radio.
Therefore, you need to rebind the event and use the $ngModel.$setViewValue() method to assign a value to the model.

 * angular directive ng-icheck
 * @require jquery, icheck
 * @example <input type="radio" ng-model="radioCheck" ng-icheck />
 *          <input type="checkbox" ng-model="checkboxCheck" ng-icheck />

myDirective.directive('ngIcheck', ['$timeout',function($timeout) {
    return {
        require: 'ngModel',
        link: function($scope, element, $attrs, ngModel) {
            return $timeout(function() {
                $scope.$watch($attrs['ngModel'], function (newValue) {

                return $(element).iCheck({
                    checkboxClass: 'icheckbox_minimal-blue',
                    radioClass: 'iradio_minimal-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($attrs['value']);

Tags: AngularJS angular JQuery

Posted on Mon, 04 May 2020 21:00:01 -0400 by jkatcher