ng-class one time binding

前端 未结 3 544
囚心锁ツ
囚心锁ツ 2021-01-01 08:58

I\'m wondering if it\'s possible to have a ng-class with class one time binded and class which are evaluated each digest cycle.

相关标签:
3条回答
  • 2021-01-01 09:30

    Method 1:

    class="some-class {{::expression ? 'my-class' : ''}}"
    

    Method 2:

    ng-class="::{'my-class': expression}"
    
    0 讨论(0)
  • 2021-01-01 09:31

    One way I can think of doing this (if I followed what you were trying to say) is as follows...

    .blue{
        color: blue;
    }
    .underline{
        text-decoration: underline;
    }
    .lineThrough{
        text-decoration: line-through;
    }
    
    <div ng-app ng-controller="myCtrl">
        <p ng-class="{'blue': isMonkey()}" class="{{isUnicorn() ? dynamicClass: ''}}">My Text</p>
        <button ng-click="monkey = !monkey">Monkey</button>
        <button ng-click="unicorn = !unicorn">Unicorn</button>
        <button ng-click="toggleClass()">Toggle</button>
    </div>
    
    function myCtrl($scope) {
        $scope.dynamicClass = "underline";
        $scope.monkey = true;
        $scope.unicorn = true;
        $scope.isMonkey = function () {
            return $scope.monkey;
        }
        $scope.isUnicorn = function () {
            return $scope.unicorn;
        }
        $scope.toggleClass = function(){
            $scope.dynamicClass = $scope.dynamicClass === "underline"? "lineThrough": "underline";
        }
    }
    

    JSFiddle

    0 讨论(0)
  • 2021-01-01 09:43

    An important part of one time binding is that it not be bound until the 'expression' is not undefined. The best answer so far, by @ifadey, his Method 1 evaluates to an empty string when 'expression' is undefined, which get's bound. This is contrary to the expected feature behavior. Method 2 is equally unhelpful in this late binding scenario.

    Do do this correctly, directly answering op's question:

    class="some-class {{::expression ? 'one-time-class' : undefined}}"
    ng-class="{ 'my-dynamic-class' : expression2 }"
    

    or the more technically correct but ugly:

    class="some-class {{::expression ? 'one-time-class' : (expression===undefined ? undefined : '')}}"
    
    0 讨论(0)
提交回复
热议问题