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) {
}]);
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) {
}]);
Share
Improve this question
asked Apr 21, 2016 at 14:20
Jim PeetersJim Peeters
2,88310 gold badges35 silver badges55 bronze badges
2 Answers
Reset to default 4Try 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() }">
Only properties of $scope
are accessible to the view. So when you say MainController.CustomService.isGreen
in the view, Angular tries to access $scope.MainController.CustomService.isGreen
, which does not exist. You should publish the service to the scope in your controller.
App.controller('MainController', ['$scope', 'CustomService', function($scope, CustomService) {
$scope.CustomService = CustomService;
}]);
Then you can access your service from the view like this:
<div ng-class="{ 'green' : CustomService.isGreen }">
</div>
Another slightly different, more popular approach is to instruct the controller to publish itself in the scope. You do this by tweaking the ng-controller
value to MainController as $ctrl
(the name could be anything but Angular 1.5 standardized $ctrl). Then $ctrl
bees available in your view:
<div ng-class="{ 'green' : $ctrl.CustomService.isGreen }">
</div>
In the controller function, $ctrl
corresponds to this
, so to publish the service, you would do:
App.controller('MainController', ['CustomService', function(CustomService) {
this.CustomService = CustomService;
}]);
Notice you don't need to inject $scope
as a parameter now.