ng-class one time binding

2019-02-11 15:46发布

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.

<div ng-class="{'one_time_binded_class': isMonkey(), 'not_one_time_binded_class': isUnicorn()}"></div>

I know I can one time bind the complete ng-class with ng-class="::{...}" but my need is to one time bind a particular expression

Of course, this thing doesn't work :

<div ng-class="{'my_static_class': ::isMonkey(), 'my_dynamic_class': isUnicorn()}"></div>

Is there a way to do it ?

3条回答
相关推荐>>
2楼-- · 2019-02-11 16:23

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

查看更多
Juvenile、少年°
3楼-- · 2019-02-11 16:25

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 : '')}}"
查看更多
冷血范
4楼-- · 2019-02-11 16:38

Method 1:

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

Method 2:

ng-class="::{'my-class': expression}"
查看更多
登录 后发表回答