angular-ui-switch
angular-ui-switch copied to clipboard
How can I get "ng-true-value" & "ng-false-value" working ?
Hi,
As in the pure following angular example
<input type="checkbox" ng-model="theColor" ng-true-value="'green'" ng-false-value="'red'"> theColor={{theColor}}
Using following html code
<switch name="theColor" ng-model="theColor" on="green" off="red" ng-true-value="'green'" ng-false-value="'red'" class="wide"></switch>
I tried to evolve the directive by implementing ngTrueValue & ngFalseValue as follow (just after the "[...]attrs.ngModel[...]", around line 20 in angular-ui-switch.js)
html += attrs.ngTrueValue ? ' ng-true-value="' + attrs.ngTrueValue + '"' : '';
html += attrs.ngFalseValue ? ' ng-false-value="' + attrs.ngFalseValue + '"' : '';
It did not work...:( Any clue ? help ? advice ?
Bellow, the full directive
/*____________________________________*/
angular.module('uiSwitch', [])
.directive('switch', function(){
return {
restrict: 'AE'
, replace: true
, transclude: true
, template: function(element, attrs) {
var html = '';
html += '<span';
html += ' class="switch' + (attrs.class ? ' ' + attrs.class : '') + '"';
html += attrs.ngModel ? ' ng-click="' + attrs.ngModel + '=!' + attrs.ngModel + (attrs.ngChange ? '; ' + attrs.ngChange + '()"' : '"') : '';
html += ' ng-class="{ checked:' + attrs.ngModel + ' }"';
html += '>';
html += '<small></small>';
html += '<input type="checkbox"';
html += attrs.id ? ' id="' + attrs.id + '"' : '';
html += attrs.name ? ' name="' + attrs.name + '"' : '';
html += attrs.ngModel ? ' ng-model="' + attrs.ngModel + '"' : '';
html += attrs.ngTrueValue ? ' ng-true-value="' + attrs.ngTrueValue + '"' : '';
html += attrs.ngFalseValue ? ' ng-false-value="' + attrs.ngFalseValue + '"' : '';
html += ' style="display:none" />';
html += '<span class="switch-text">'; /*adding new container for switch text*/
html += attrs.on ? '<span class="on">'+attrs.on+'</span>' : ''; /*switch text on value set by user in directive html markup*/
html += attrs.off ? '<span class="off">'+attrs.off + '</span>' : ' '; /*switch text off value set by user in directive html markup*/
html += '</span>';
return html;
}
}
});
/*____________________________________*/
Regards Lionel
If you want to use ngTrueValue/ngFalseValue then part ''ng-click="' + attrs.ngModel + '=!' + attrs.ngModel" is not valid as it assumes true/false.
Replace this with the following code and will work:
ng-click="' + attrs.ngModel + '= ' + attrs.ngModel + '=== ' + (attrs.ngTrueValue || true) + '? ' + (attrs.ngFalseValue || false) + ' : ' + ( attrs.ngTrueValue || true) +
you can try this: https://github.com/hjzheng/angular-switch