cgarvis / angular-toggle-switch

AngularJS Toggle Switch
http://cgarvis.github.io/angular-toggle-switch
MIT License
160 stars 124 forks source link

ng-class support? #51

Closed jgentes closed 10 years ago

jgentes commented 10 years ago

I haven't been able to get ng-class to work with toggle-switch:

<toggle-switch ng-model="adminStatus" ng-class="{ 'switch-on' : true }" style="margin-bottom: 5px;" class="danger" on-label="Yes" off-label="No"><toggle-switch>

I get errors like:

Error: [$parse:syntax] Syntax Error: Token '{' is an unexpected token at column 24 of the expression [{ 'switch-on' : true } { 'disabled': disabled }] starting at [{ 'disabled': disabled }].

So it's clearly using ng-class to inject the { 'disabled': disabled } but I'm not sure how to add another ng-class expression in with it.

Any ideas?

cgarvis commented 10 years ago

Might make sense to just wrap the toggle in a div with your custom class.

jgentes commented 10 years ago

Thanks for the suggestion. This is a toggle-switch class, though:

<div class="switch-on">
  <toggle-switch ng-model="adminStatus" style="margin-bottom: 5px;" class="danger" on-label="Yes" off-label="No"><toggle-switch>
</div>

So it doesn't work unless included in <toggle-switch>.

However, I just noticed this:

ng-class="{'switch-off': !model, 'switch-on': model}"

So I may be able to manipulate the model to get the switch to the state I want. But it would be nice to be able to use ng-class rather than mess with the model beforehand.

jgentes commented 10 years ago

Actually I was able to get around it with ng-init:

ng-init="adminStatus = isAdmin"

Now to figure out disabled..

jgentes commented 10 years ago

Got it, I was able to address with disabled="!isAdmin"

cgarvis commented 10 years ago

You can also set the model in your controller. I tend to have init functions that set default values.

angular.module('Admin', [])
  .controller('AdminCtrl', function($scope, User) {
    (function init() {
      $scope.isAdmin = false;
    })();

    User.get().$promise.then(function(user) {
      $scope.isAdmin = user.role === 'admin';
    });
  });