AngularJS ng-class multiple conditions with OR operator

后端 未结 5 675
予麋鹿
予麋鹿 2021-02-07 01:51

I try to find out the good syntax for adding classes depending on angular values. I want to activate a class regarding 2 conditions (one on live user changes, and one on loading

5条回答
  •  无人共我
    2021-02-07 02:37

    Once you have to add some logic behind ng-class it's always better to stick to using the controller to do that. You can do it two of either ways: JSON syntax (same as in your HTML, just more readable) or obviously JavaScript.

    HTML (JSON) Syntax

    HTML

    
    

    JS

    $scope.getFavClassIcon= function (favId) {
        return {
            'fa-star-o' : !$scope.favorite,
            'fa-star'   : $scope.favorite || $scope.fav === favId
        };
    };
    

    Good Old IF-statement (JavaScript)

    HTML

    
    

    JS

    $scope.getFavClassIcon= function (favId) {
        if (!$scope.favorite) {
            return 'fa-star-o';
        } else if ($scope.favorite) { // obviously you can use OR operator here
            return 'fa-star';
        } else if ($scope.fav === favId) {
            return 'fa-star';
        }
    };
    

提交回复
热议问题