2

I have this div somewhere in my code.

<div ng-class="className" >{{className}}</div>

At some point I am calling changeClass function from an ng-click to change the class of this div.

     $scope.changeClass = function(){
          console.log($scope.className)
              if ($scope.className === "expand-icon")
                 $scope.className = "expand-icon.expanded";
              else
                 $scope.className = "expand-icon";
  };

I can see the class changes because of the console.log and also the {{className}} is outputed on the page. However the css class doesn't seem to be applied.

It's in fact a '+' sign that needs to turn into a '-' with an animation. Here's the css:

 /* + button */

.expand-icon {
  height: 32px;
  width: 32px;
  position: relative;
}
.expand-icon::before, .expand-icon::after {
  content: " ";
  width: 32px;
  height: 6px;
  background-color: #fff;
  display: block;
  position: absolute;
  top: 50%;
  left: 50%;
  transition: all 0.15s cubic-bezier(.42, 0, .58, 1);
  opacity: 1;
  border-radius: 2px;
}
.expand-icon::before {
  transform: translate(-50%, -50%) rotate(90deg);
}
.expand-icon::after {
  transform: translate(-50%, -50%);
}

.expand-icon {
  height: 32px;
  width: 32px;
  position: relative;
}
.expand-icon.expanded::before {
  transform: translate(-50%, -50%) rotate(0deg);
}
.expand-icon.expanded::after {
  transform: translate(-50%, -50%) rotate(-90deg);
  opacity: 0;
}

So the expand-icon is applied but expand-icon.expanded doesn't have any affect since I'm using this ng-class trick. Any idea why?

2
  • 2
    You should replace the dot with a space: $scope.className = "expand-icon expanded"; Commented Dec 15, 2016 at 13:12
  • possible duplicate stackoverflow.com/questions/20460369/… Commented Dec 15, 2016 at 13:21

3 Answers 3

3

You should replace the dot with a space: $scope.className = "expand-icon expanded";

Or better, use the other notation of ng-class:

// probably rename it to something like $scope.toggleExpanded()
$scope.changeClass = function(){
    $scope.expanded = !$scope.expanded;
};

And in your html:

<div class="expand-icon"
     ng-class="{ expanded: expanded }">{{className}}</div>

This will apply your expand-icon class always, and the expanded class only when the $scope.expanded property is truthy.

Sign up to request clarification or add additional context in comments.

Comments

0

ng-class="className" is for expression. for example: ng-class="{classNam:true}".

in this case you can just do like this: class="{{className}}"

Comments

0

Try this

<div class="{{className}}">{{className}}</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.