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
}
Related
I'm working with a page which displays a product's price. Normally it looks like this:
<span id="priceText">
$26.94
</span>
When the item is on sale, it looks like this:
<span id="priceText">
<strike>$26.94</strike>
<span class="salePrice">$25.00</span>
</span>
I have a generic function which extracts the price from any page like so:
var getPrice = function(price_id) {
return jQuery(price_id).text();
};
Where price_id is the id of the element which contains the price.
As is plainly obvious, this will not work with the above structure since the "sale" version will return both $26.94 and $25.00 if I set price_id to priceText
I do not have control over the html on the product's page, so I can't change the structure. I need to use the getPrice function on other pages which do not have this HTML structure, so I also want to avoid changing it.
What I am looking for is some sort of jQuery selector which will return $25.00 if the item is on sale, or $26.94 if it isn't. Something like "return all text inside of priceText NOT in a strike tag"
I currently have a custom snippet which does the following:
jQuery('#priceText .salePrice').length ? jQuery('#priceText .salePrice').text() : jQuery('#priceText strike').text()
However I want to avoid custom lines of code like this. I think this may not be possible using only jQuery selectors but I'm hoping someone proves me wrong!
You can use a multiple selector.
jQuery('#priceText .salePrice, #priceText:not(:has(.salePrice))').text()
DEMO
Maybe you could reduce your condition by this:
($('#priceText .salePrice') || $('#priceText strike')).text()
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 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';
}
I am trying to figure out a simple way to swap a link in a button in angular js, I have properties available in the scope that I can use, but I am not sure how to implement. The link I am trying to alter is in the 'onClick' attribute in the button. Thanks again in advance, here is my code:
<div class="instructions-button">
<button
type="button"
class="halo-modal-action-button external-instructions"
onClick="window.open('https://mysite/foo');"
window="new"
ng-disabled=""
ng-click=""
data-bs-enabled=""
>Instructions</button>
</div>
I am trying to make a simple conditional to show either:
'mysite/foo || mysite/bar'
but am not sure how to make it work.
Don't use onClick event on the button, although it might feel weird to you, since you are coming from vanilla JS, you should use ng-click.
<button
class="halo-modal-action-button external-instructions"
ng-disabled=""
ng-click="openWindow()"
data-bs-enabled=""
>Instructions</button>
and inside controller
$scope.openWindow = function(){
if ( condition ) {
open('http:foo.bar')
} else {
open('http:bar.foo')
}
}
Two simple ways to do this.
1) Two buttons and show one conditionally with ng-show.
<button ... ng-show="conditionShowFooTrue" >
<button ... ng-show="conditionShowBarTrue" >
2) Use ng-click to call a scope function to conditionally sets the url as the other answers have suggested.
If you're using routes, you can just use ng-click like #Akxe said, and with the $location service in your controller, do:
$scope.changeLocation = function(){
if(condition)
{
$location.path('/foo');
} else
{
$location.path('/bar');
}
};
I think that would be the Angular way to do this.
Is there a way in which ng-init will get updated when tableCells will change ? I want to use this approach (or similar) so angular won't have to call findCellsByDate two times.
I also tried to change ng-init with ng-bind or ng-model, but bind will show [object Object] and model will throw an error as there isn't an attribution.
<span ng-init='cells = findCellsByDate(tableCells, day)'>
<div class='text' ng-show='forecastAndActualForCellsAreNotEmpty(cells)'>
<span ng-bind='getTotalHoursPercentageForCells(cells)'></span>
<span>%</span>
</div>
</span>
I don't think ng-init works that way, so what I'm thinking is that you should change some of your controller/model code to hold a boolean for forecastAndActualForCellsAreNotEmpty which would get updated.
On the other hand you could do it by css. I assume that if forecastAndActualForCellsAreNotEmpty returns false, getTotalHoursPercentageForCells would return 0. So you could bind that to a data attribute and using a css rule make the div go away. But in order to not use ng-init you would have to take the content also with css. And the only way to do that, that I know of, is with :before and :after.
Something like
<div class='text' data-percentage='{{getTotalHoursPercentageForCells(findCellsByDate(tableCells, day))}}'>
</div>
And the css
div[data-percentage=0]{
display: none;
}
div[data-percentage]:before{
content: attr(data-percentage) "%";
display: block;
}
Now I wouldn't use :before or :after to display actual application content, but rather things that are related to style. So I suppose the final recommendation would be to alter the model instead.
You can put the logic that changes the cells variable inside a watch function that observe changes in tableCells variable
$scope.$watch('tableCells', function(tableCells) {
if(!tableCells) return;
$scope.cells = findCellsByDate(tableCells, $scope.day);
});
In this way you keep that logic in the controller