I have a div like this
<div ng-model="star"></div>
I want to add a class 'active' to this div in angular js.
I tried like this in my angular js controller
$scope.star.addClass('active');
But,I am getting error. I am new to angular js. please help me...
Try this:
<div ng-class="{ active: star == 'yes', 'in-active': star == 'no' }" ng-bind="star"></div>
You can have one or more classes assigned based on the expression (true or false).
If a class name has a hyphen, enclose in single quote.
This is a better approach and preferred than changing in controller.
Also, because this is a div, you have to do ng-bind, not ng-model.
ng-model works on fields like input.
UPDATE:
Since you insist on changing the class in code, here it is:
$("div[ng-bind='star']").addClass('active');
If you want to access change class dynamically then you can put watch on your star variable in your controller like below :
$.watch('star',function(newVal, oldVal){
// put your code to here based on new value and old value
// you can add class to your div like :
// angular.element("div[ng-bind='star']").addClass('active');
});
Using a variable to control your class
<div ng-class="customClass"></div>
in controller
$scope.customClass = 'active custom-class1';
so, you can use if-else to change class name
if (something) {
$scope.customClass = 'active custom-class1';
} else {
$scope.customClass = 'deactive custom-class2';
}
Related
Hi I'm making a a drag directive but because of the way it works I can't get it to work on dynamic objects as it calls the id in the input.
#Input()
set Drag(options: any) {
this.stickerElement = document.getElementById(options.id);
}
Which works fine when the element isn't dynamic:
<div id="sticker" class="issues" [Drag]="{id: 'sticker'}">
but when it's set dynamically I can't figure out how to interpolate the ID dynamically.
<div [attr.id]="'Session' + Day.id" [Drag]="{id:'Session' + Day.id}"></div>
I've tried setting this.stickerElement with the #HostListener when you use it but that allows the directive to bubble and use child elements. I guess I can work around it but it doesn't feel right.
I feel like I'm missing some knowledge because no matter what I google nothing useful comes up about how to interpolate it correctly. Can you interpolate an attribute into a directive like this?
Thanks in Advance
B
I don't see any issue in the interpolation. However, document.getElementById(options.id) in Angular looks dirty. Instead you could use a template reference variable and directly send the HTMLElement.
Try the following
Template
<div appSticker #sticker [Drag]="{ref:sticker}"></div>
Directive
#Directive({ selector: "[appSticker]" })
export class StickerDirective {
stickerElement: HTMLElement;
#Input()
set Drag(options: any) {
this.stickerElement = options.ref;
}
constructor() {}
}
Also I don't see the directive binding in the <div> tag in your code.
I'm trying to have a checkbox, so when you click on the default FontAwesome empty box (fa-square-o) it gets changed with this icon (fa-check-square-o).
How can I do that with AngularJS? I need to put a function in the controller and call it from ng-click? What would be the correct function?
I found what I need in Jquery but would love to just use angular for it:
$("#checkBoxOn").click(function(event) {
$(this).find('i').toggleClass('fa-check-square-o');
If possible help me convert this in Angular!
Two parts:
You need something that holds a boolean if something is checked. We can do that using an expression like this: ng-click="toggle = !toggle". Basically, each time you click the element with that directive, toggle will become what it wasn't before.
You can use a ternary operator to set the class: i ng-class="toggle ? 'fa-check-square-o' : 'square-o'"></i>
Together, this might become something like:
<span ng-click="toggle = !toggle">
<i ng-class="toggle ? 'fa-check-square-o' : 'square-o'"></i>
Some text with the toggle here, that is also clickable.
</span>
Based on your other question, to hide another element based on this, you can add ngHide to it:
<table ng-hide="toggle">
This question is similar to AngularJS toggle class using ng-class, but that does not answer the toggling portion.
Just to make it more interesting, you could do something with unicode instead if you don't want the extra dependencies. This uses ngShow and ngHide.
<span ng-click="toggle=!toggle">
<span ng-show="toggle">☐</span>
<span ng-hide="toggle">☑</span>
Some text with the checkbox here
</span>
You don't need to use jQuery, use ngClass, to change the classes according to what a variable holds
<checkbox ng-click="value = !value">
<span class="fa" ng-class="{'fa-square-o': !value , 'fa-check-square-o': value}"></span>
You need ngChecked.
When you change the checkbox, apply your method:
ng-checked="MyMethod()"
The most easiest example:
input type='checkbox' ng-checked='MyMethod()' />
Script:
$scope.MyMethod = function() {
//your logic
return true; //checked
}
I have a bootstrap themed angular app that has 2 radio buttons that bring up separate pages. Both can't be selected at the same time. When one is selected I want the btn btn-primary active to be the class values while the other one which is not selected has the class attributes btn btn-secondary.
I've spent hours google searching and playing around with different things and nothing has worked. Here's the plunker with my attempt so far. Any idea what I'm doing wrong?
A few things that are off-
You didn't include AngularJS. Of course it won't run, it's not there at all...
You're trying to use ng-class as a class the wrong way. Aside from the fact that using the ng-class attribute is generally easier*, you have it formatted wrong. You have ng-class=!view.isSelected ? 'btn-primary active' : 'btn-secondary', which should be ng-class:!view.isSelected ? 'btn-primary active' : 'btn-secondary'. Note the : instead of the = sign.
*This is not to say that you can't use the class version of ng-class (it's definitely valid to do so), but I'd generally make the distinction to have static classes in the class attribute, and anything dynamic in ng-class.
You have no controller. While technically you can cause the view to "truthily" create a scope variable by negating undefined (which is a very sloppy way of doing it), this will at best allow you to have one binary/toggle radio set, or a set of mutually allowed toggles. You should have, in your controller, a scope variable that holds which button is pressed (each button setting it on click to something to indicate it's now them), and having ng-class evaluate for that.
in your plunker demo didn't use bootstrap to use class btn btn-primary btn-secondary so add bootstrap link.
and invalid expression for ng -class. should use
class="btn" ng-class="button.view1Selected ? 'btn-primary active' : 'btn-secondary'"
insted of
class="btn ng-class:button.view1Selected ? 'btn-primary active' : 'btn-secondary'"
Better to use an array to store all view buttons info with selected property that initially false.
like:
$scope.views = [{isSelected: false},{isSelected: false}];// index based 0 for 1st button ...` or can be specific property based as you need
and when clicked on any button then set that button is selected and set class according to your condition.Call a function to set specific button active flag.
like: ng-click="selectedButton(1)"
and check to set class like: ng-class="views[0].isSelected ? 'btn-primary active' : 'btn-secondary'"
selectedButton function like:
$scope.selectedButton = function(viewIndex){
angular.forEach($scope.views, function(view, index) {
if(viewIndex == index) {
view.isSelected = ! view.isSelected;
} else {
view.isSelected = false;
}
});
};
See Plunker Demo
i want to get the text of div using angularjs . I have this code
<div ng-click="update()" id="myform.value">Here </div>
where as my controller is something like this
var myapp= angular.module("myapp",[]);
myapp.controller("HelloController",function($scope,$http){
$scope.myform ={};
function update()
{
// If i have a textbox i can get its value from below alert
alert($scope.myform.value);
}
});
Can anyone also recommand me any good link for angularjs . I dont find angularjs reference as a learning source .
You should send the click event in the function, your html code should be :
<div ng-click="update($event)" id="myform.value">Here </div>
And your update function should have the event parameter which you'll get the div element from and then get the text from the element like this :
function update(event)
{
alert(event.target.innerHTML);
}
i just thought i put together a proper answer for everybody looking into this question later.
Whenever you do have the desire to change dom elements in angular you need to make a step back and think once more what exactly you want to achieve. Chances are you are doing something wring (unless you are in a link function there you should handle exactly that).
So where is the value comming, it should not come from the dom itself, it should be within your controller and brought into the dom with a ng-bind or {{ }} expression like:
<div>{{ likeText }}</div>
In the controller now you can change the text as needed by doing:
$scope.likeText = 'Like';
$scope.update = function() {
$scope.likeText = 'dislike';
}
For angular tutorials there is a good resource here -> http://angular.codeschool.com/
Redefine your function as
$scope.update = function() {
alert($scope.myform.value);
}
A better way to do it would be to use ng-model
https://docs.angularjs.org/api/ng/directive/ngModel
Check the example, these docs can be a bit wordy
I need to add the class error to a <label> with the name attribute set to choice_16_0. The code I wrote to do this, however, changes every label on the page to <label for="choice_16_0" class="error">, instead of just adding the new class to the label that already contains for="choice_16_0".
Here's my code:
if (!$("input[#name=\"choice_16_0\"]:checked").val()) {
$("label").attr("for","choice_16_0").addClass("error");
};
What's wrong with this, and how can I fix it?
You selector $("label") is what's selecting every label on the page, change it to $("label[name=choice_16_0") to have it select the single label with the name you want.
var field = $("input[#name=\"choice_16_0\"]:checked");
if (!$(field).val()) {
$(field).attr("for","choice_16_0").addClass("error");
error = true;
};
In jQuery, .attr(attribute, value) is a setter while .attr(atribute) is a getter. You should use selectors instead: $("label[for=choice_16_0]").addClass("error")