Created
October 23, 2014 12:09
-
-
Save amcdnl/660a429fffb4b3eaf6cc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
define(['angular'], function (angular, $) { | |
// Use to style checkboxes, bind checkboxes to arrays, and run validators on checkboxes | |
// Modified from: https://github.com/bkuhl/angular-form-ui/tree/master/src/directives/checkBox | |
var module = angular.module('components.checkbox', []); | |
/** | |
* <check-box ng-model="isChecked()"></check-box> | |
* Required attribute: ng-model="[expression]" | |
* Optional attribute: value="[expression]" | |
*/ | |
module.directive('checkBox', function () { | |
return { | |
replace: true, | |
restrict: 'E', | |
scope: { | |
'externalValue': '=ngModel', | |
'value': '&' | |
}, | |
require: 'ngModel', | |
template: function (el, attrs) { | |
var html = '<div class="ngCheckBox' + ((angular.isDefined(attrs.class)) ? ' class="'+attrs.class+'"' : '') + '">'+ | |
'<span ng-class="{checked: isChecked}">' + | |
'<input type="checkbox" ng-model="isChecked"' + ((angular.isDefined(attrs.id)) ? ' id="'+attrs.id+'"' : '') + '' + ((angular.isDefined(attrs.name)) ? ' name="'+attrs.name+'"' : '') + '' + ((angular.isDefined(attrs.required)) ? ' name="'+attrs.required+'"' : '') + '/>'+ | |
'</span>'+ | |
'</div>'; | |
return html; | |
}, | |
controller: function ($scope) { | |
if (angular.isArray($scope.externalValue)) { | |
$scope.isChecked = $scope.externalValue.indexOf($scope.value()) >= 0; | |
} else { | |
$scope.isChecked = !!$scope.externalValue; | |
} | |
$scope.$watch('isChecked', function (newValue, oldValue) { | |
if (angular.isDefined(newValue) && angular.isDefined(oldValue)) { | |
//add or remove items if this is an array | |
if (angular.isArray($scope.externalValue)) { | |
var index = $scope.externalValue.indexOf($scope.value()); | |
if(newValue) { | |
if( index < 0 ) $scope.externalValue.push($scope.value()); | |
} else { | |
if( index >= 0 ) $scope.externalValue.splice(index, 1); | |
} | |
} else { | |
//simple boolean value | |
$scope.externalValue = newValue; | |
} | |
} | |
}); | |
}, | |
link: function ($scope, $elm, $attrs, ngModel) { | |
$scope.$watchCollection('externalValue', function(newVal) { | |
if (newVal.length) { | |
ngModel.$setTouched(); | |
ngModel.$commitViewValue(); | |
ngModel.$validate(); | |
} | |
}); | |
} | |
}; | |
}); | |
return module; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment