Search code examples
javascriptangularjsng-class

How to use ng-class with a boolean from a service in angular.js ?


I want to set a class based on the boolean that I set in a service. This is a simplified version from my code (for the sake of readability). The boolean is normally set by a lot of other functions in this service.

HTML :

<div ng-controller="MainController">
    <div ng-class="{ 'green' : MainController.CustomService.isGreen }">
    </div>
</div>

Service :

App.service("CustomService", function() {
    this.isGreen = true;
})

Controller :

App.controller('MainController', ['$scope', 'CustomService',  function($scope, CustomService) {

}]);

Solution

  • Try this way:

    App.controller('MainController', ['$scope', 'CustomService',  function($scope, CustomService) {
        $scope.isGreen = CustomService.isGreen;
    }]);
    

    HTML:

    <div ng-class="{ 'green' : isGreen }">
    

    View does not have direct access to service. View has access to $scope object, So if you need something in view, you shall write in $scope first.

    If you want to track color:

    App.controller('MainController', ['$scope', 'CustomService',  function($scope, CustomService) {
        $scope.isGreen = function () {
            return CustomService.isGreen;
        };
    }]);
    

    And:

    <div ng-class="{ 'green' : isGreen() }">