Dynamic class in Angular.js

后端 未结 4 2082
旧巷少年郎
旧巷少年郎 2020-12-02 17:00

I want to dynamically add a css class to an

  • element I am looping over. The loop is like this:

  • 4条回答
    •  时光说笑
      2020-12-02 17:34

      You can simply assign a function as an expression and return proper class from there. Edit: there is also better solution for dynamic classes. Please see note below.

      Snippet from view:

      ...

      and in the controller:

      $scope.appliedClass = function(myObj) {
          if (myObj.someValue === "highPriority") {
              return "special-css-class";
          } else {
              return "default-class"; // Or even "", which won't add any additional classes to the element
          }
      }
      

      Better way of doing this

      I've recently learned about another approach. You pass in an object which has properties corresponding to the classes you operate on, and the values are expressions or boolean variables. A simple example:

      ng-class="{ active: user.id == activeId }"

      In this case active class will be added to the element as long as user.id matches activeId from the $scope object!

    提交回复
    热议问题