如何将 ng-class 与 angular.js 中服务的布尔值一起使用?

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

我想根据我在服务中设置的布尔值设置一个 class。这是我的代码的简化版本(为了便于阅读)。该布尔值通常由该服务中的许多其他函数设置。

HTML :

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

服务:

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

控制器:

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

}]);

试试这个方法:

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

HTML:

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

视图无法直接访问服务。视图可以访问$scope对象,所以如果你需要视图中的东西,你应该先写在$scope

如果要跟踪颜色:

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

并且:

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

视图只能访问 $scope 的属性。因此,当您在视图中说 MainController.CustomService.isGreen 时,Angular 会尝试访问不存在的 $scope.MainController.CustomService.isGreen。您应该将服务发布到控制器中的范围。

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

然后您可以从这样的视图访问您的服务:

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

另一种略有不同但更流行的方法是指示控制器在作用域中发布自身。您可以通过将 ng-controller 值调整为 MainController as $ctrl(名称可以是除 Angular 1.5 标准化 $ctrl 之外的任何名称)来执行此操作。然后 $ctrl 在您的视图中可用:

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

controller函数中,$ctrl对应this,所以要发布服务,你会做:

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

请注意,您现在不需要将 $scope 作为参数注入。