Reputation: 540
I have two places need to add a css class called myClass
dynamically. I only want to add this class when $root.myBool
is true. I got one of them work using this:
<ion-side-menu-content class="ng-class: $root.myBool ? 'myClass' : ''">
But I can't get the other one work. Here's the issue, this one above is written in cshtml directly. But the other one is added using angularJS inside javascript file. The other one looks like this in .js file var container = jqLite("<div class='class1 class2'>");
I want to add myClass
right after class2, something like:
var container = jqLite("<div class='class1 class2 ng-class: $root.myBool ? 'myClass' : '''>");
I tried, but couldn't make it work. Hope someone can help..
Also I have a second idea to achieve this, since myClass
is really only one line of style:
.myClass {
top: 78px;
}
So I was thinking maybe I also can change the top attribute inside javascript. So I'll add the class like this var container = jqLite("<div class='class1 class2 myClass'>");
Then change the top
attribute inside the javascript where I change myBool
:
$scope.myBool = false;
//get 'myClass' somehow and change the attribute 'top' here.
I know for jQuery I can do $('.myClass').css("top", "0px");
. But I'm using ionic here, so the syntax is different, that's my issue.
So there're two ways I can think of to do this, make either one works will be more than enough for me. Thanks a lot!
Upvotes: 2
Views: 976
Reputation: 5020
If you generate HTML on the fly, you need to $compile
it:
$compile(container)(scope);
Furthermore, I think writing ngClass as its own attribute in the form of ng-class="{'myClass': $root.myBool}"
is much cleaner and less error-prone than the form inside a class
attribute.
Tying it together:
var container = "<div class='class1 class2' ng-class=\"{'myClass': $root.myBool}\">";
element.append($compile(container)($scope);
There's not need to run it through jqLite before compiling it.
Upvotes: 3
Reputation: 6205
In my opinion you could use simply ngClass
and ngStyle
:
Controller:
$scope.topPx = '20px';
HTML:
<ion-side-menu-content ng-class="{'myClass': $root.myBool}" ng-style="{'top': topPx}">
Upvotes: 0