add class to multiple selector after click Angular - javascript

i want to add class to multiple divs after click on button.
here is my code :
$scope.noneStyle = "noneVisible";
$scope.bodyCon = "notRotate";
$scope.addStyle = function () {
if ($scope.noneStyle === "noneVisible" && $scope.bodyCon ==="notRotate") {
$scope.noneStyle = "visibleStyle";
$scope.bodyCon = "rotate";
}
else
$scope.noneStyle = "noneVisible";
$scope.bodyCon = "notrotate";
}
HTML
Click
<aside class="rightbar {{noneStyle}} {{visibleStyle}}"></aside>
<div class="container-fluid {{bodyCon}} {{rotate}}"></div>
here is the Demo:http://jsfiddle.net/sadeghbayan/dbnb2f9x/

You are trying to print scope variables in your markup visibleStyle and rotate that are not defined in the scope.
You are using these names as strings, not javascript variables. Fix this, and everything should work fine.

The reason why your solution isn't working, is because the {{noneStyle}} is immediately parsed as text.
You can use ng-class to achieve this.
I've edited your JsFiddle to achieve this:
http://jsfiddle.net/dbnb2f9x/3/
myApp.controller('mainCtrl', function ($scope) {
$scope.noneStyle = false;
$scope.bodyCon = false;
//Toggle the styles
$scope.toggleStyle = function () {
//If they are true, they will become false
//and false will become true
$scope.bodyCon = !$scope.bodyCon;
$scope.noneStyle = !$scope.noneStyle;
}
});
and in the HTML:
<div ng-app="myApp" ng-controller="mainCtrl">
Click
<aside ng-class="{'noneStyle' : noneStyle}"class="rightbar"></aside>
<div ng-class="{'bodyCon' : bodyCon}" class="container-fluid"></div>
</div>
when the bodyCon $scope variable is true, the class 'bodyCon' will be added to the div because of this rule:
ng-class="{'bodyCon' : bodyCon}"
You can add mutliple statements:
ng-class="{'bodyCon' : bodyCon, 'helloWorldClass' : myVariable == 'helloWorld'}"
In above example the class: "helloWorldClass" will be added when $scope.myVariable equals 'helloWorld'
Hope this helps you with your problem!

Related

How to convert this jQuery code in an AngularJS code?

I'm facing the following issue: I'm working with Angular1.x and I have a subpage with small, clickable images and some other stuff below these imgs.
Only the images should be visible, all the other things should be hidden.
When the user clicks on an image, this hidden-visible has to flip, so the whole image session goes hidden and the content below comes visible.
I have a jQuery solution, but I'm seeking a more semantic one with Angular.
(function($){
$(document).ready(function(){
$('.showOverlay').click(function(){
$('#container').hide();
$('#box').show();
});
$('.hideOverlay').click(function(){
$('#container').show();
$('#box').hide();
});
});
})(jQuery);
I hope this piece of code explains the idea behind.
When you click "Show overlay", it will call the showOverlay() function, same for "Hide overlay":
<div ng-click="showOverlay()">Show overlay</div>
<div ng-click="hideOverlay()">Hide overlay</div>
<div ng-show="container">Shown when $scope.container is true</div>
<div ng-show="box">Shown when $scope.box is true</div>
Add the following functions in your controller:
$scope.showOverlay = function() {
$scope.container = false;
$scope.box = true;
}
$scope.hideOverlay = function() {
$scope.container = true;
$scope.box = false;
}
I would suggest using ng-hide:
in your html
<div ng-hide="myValue"></div>
<button ng-click="show()">show</button
<button ng-click="hide()">hide</button
then in your javascript:
$scope.show = function(){
$scope.myValue = false;
}
$scope.hide = function(){
$scope.myValue = true;
}
Is there any instance when both the container and box should be visible? If not, I dare say you should use the same variable for both of them, like so:
<img ng-src="{{img}}.png" ng-click="hideImage()" ng-show="imageShown">
<div ng-click="showImage()" ng-show="!imageShown">
And in your controller:
$scope.hideImage = function() {
$scope.imageShown = false
}
$scope.showImage = function() {
$scope.imageShown = true
}
Maintaining two variables for values that always mirror each other just seems irresponsible.

Angular find via attribute

I have problem with my script.
js
$scope.showConfirm = function(e) {
var confirmPopup = $ionicPopup.confirm({
title: 'some title',
template: 'ccccccc'
});
confirmPopup.then(function(res) {
if(res) {
var a = angular.element(document.querySelectorAll("div['data-id'="+e+"]"));
console.log(a);
}
});
};
and html:
<div class="green" data-id="{{mydiv.mydiv_id}}">
<p>some text </p>
<button class="button button-primary" ng-click="showConfirm({{mydiv.mydiv_id}})">
Wykonane
</button>
</div>
Everything works well, id is allocated and when I check the console that also is all okay, but at this stage need to click the button changed class.For example when I'm click "showConfirm()" I need change class in div where data-id = showConfirm(id).
Now my div have class green, when I' click button this class change to red. In jquery the same script view like this:
$(button).on(click, function(e){
var element = $("div[data-id="+e+"]");
element.removeClass(green);
element.addClass(red)
});
How to do it?
EDIT:
I see that I need to add full code to make it clear :)
updated code:
$scope.showConfirm = function(e) {
var confirmPopup = $ionicPopup.confirm({
title: 'title',
template: 'eeeeee'
});
confirmPopup.then(function(res) {
if(res) {
var a = angular.element(document.querySelectorAll("div['data-id'="+e+"]"));
console.log(a);
$http.get("http://example/rest_api/json?id="+e)
.success(function(data){
// if success set green
})
.error(function(){
// if error set red
})
}
});
};
I need change class when my server is success response.
You should do everything in angular way. angular.element is not the right solution.
You can use ng-class of angular.
Example
<i class="fa" ng-class="{'class-name1': condition1 == 'true', 'class-2': condition2== 'true'}"></i>
if condition 1 is true then class-name1 will be added, if condtion2 is true then class-2 class will be added.
HTML
<div ng-class="{'green': buttonClicked == true, 'red': responseInYes== true}">
$scope.showConfirm = function(e) {
$scope.buttonClicked = true;
$scope.responseInYes= false;
var confirmPopup = $ionicPopup.confirm({
title: 'some title',
template: 'ccccccc'
});
confirmPopup.then(function(res) {
if(res) {
$scope.buttonClicked = false;
$scope.responseInYes= true;
}
});
};
I guess you are looking for something like this.
Consider using ng-class instead of class.
For example
You could also do this using objects, and based on your edit it could be something like:
Updating the HTML
<div data-id="{{mydiv.mydiv_id}}" ng-class="conditions[mydiv.mydiv_id] ? 'green' : 'red'">
And in your controller $scope.conditions = {}; and just set it to true or false in your success and error like : $scope.conditions[e] = true /* or false */;
Note. If you want the default to be green just set the condition to true on init or do the validations and settings assuming the expected to be a negative value.
Try updating a property inside mydiv:
<div class="{{mydiv._class}}">
<p>some text </p>
<button class="button button-primary" ng-click="showConfirm(mydiv)">
Wykonane
</button>
</div>
Then, in your function:
$scope.showConfirm = function(e) {
// your popup window and some more code ...
e._class = 'yellow'; // class for fecthing data (waiting server json result)
$http.get(URL).success(function(data) {
e._class = 'green'; // class for success
}).error(function() {
e._class = 'red'; // class for error
});
};
Use ng-class
The ngClass directive allows you to dynamically set CSS classes on an HTML element by databinding an expression that represents all classes to be added.
Check this out.
In your case i suggest to do :
$scope.isGreen = false;
$http.get("http://example/rest_api/json?id="+e)
.success(function(data){
$scope.isGreen = true;
})
.error(function(){
})
In your Html file add this:
ng-class="{'class-green': isGreen, 'class-red': !isGreen}"

Checking visibility with jQuery (debug)

I followed a few posts to be able to check the visibility of a div :
HTML :
<div class="language" onclick="Show_Div()">
<div class="menu-langues">
//my code here
</div>
</div>
Script :
function Show_Div() {
$Div_id = "menu-langues";
if ( $(Div_id).is(':hidden')) {
($Div_id).show();
}
else {
($Div_id).hide();
}
}
Console :
Uncaught ReferenceError: Div_id is not defined
I can't see what i did wrong, can someone help me with this?
Thank's ! :)
You've defined a variable, then used a different one in your code in the if-statement.
if ( $(Div_id).is(':hidden')) {
should be
if ( $($Div_id).is(':hidden')) {
That should solve the error. However, to get working code I'd recommend writing like this:
function Show_Div() {
$Div_id = $(".menu-langues");
if ( $Div_id.is(':hidden')) {
$Div_id.show();
}
else {
$Div_id.hide();
}
}
This way you're turning the variable $Div_id into a jQuery object, on which you can execute functions. By saving it in the variable, the code doesn't have to look for the element over and over again.
Don't mix inline event handlers like onclick with jQuery. jQuery handlers will do a better job and have extra features. And, as #Rory McCrossan said, just use toggle.
Code:
$('.language').click(function(){
// Show if hidden and hide if visible
$('.menu-langues').toggle();
});
Html (no inline handler):
<div class="language">
<div class="menu-langues">
//my code here
</div>
</div>
If you had multiples of the same button on the page, you can target the selection using a scoped selector (second parameter defines the scope):
$('.language').click(function(){
// Show if hidden and hide if visible
$('.menu-langues', this).toggle();
});
Some errors: menu-langues is a class not an ID, so, you can reference this with jQuery as: $('.menu-langues')
If you need reference to an ID, use jQuery: $('#menu-langues')
So, use '.' to reference a class and '#' to reference an ID.
You used $Div_id = "menu-langues"; ...and I changed it to: Div_id = "menu-langues";
And too you write $(Div_id).show(); and I fixed to: $(Div_id).show();
The snipped code fixed and working:
function Show_Div() {
var Div_id = ".menu-langues"; // is a class, not ID
if ( $(Div_id).is(':hidden')) {
$(Div_id).show();
}
else {
$(Div_id).hide();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="language" onclick="Show_Div()">
<div class="menu-langues">
test of visibility
</div>
</div>
<button onClick="javascript:Show_Div();">Click</button>
Your variable name is $Div_id not Div_id. Also you are trying to select with class name so you would need to prepend a . to your selector.
Your code should look like:
function Show_Div() {
$Div_id = ".menu-langues";
if ( $($Div_id).is(':hidden')) {
$($Div_id).show();
}
else {
$($Div_id).hide();
}
}
The code should be more like:
function Show_Div() {
var $Div_id = "menu-langues";
if ( $($Div_id).is(':hidden')) {
$($Div_id).show();
} else {
$($Div_id).hide();
}
}
It's also worth mentioning that the convention for JavaScript variable names and function names is camelCase.

JQuery Toggle True or False on data-filter

I have an image link which I want to use as a toggle button.
<img id="myToggleButton" src="myToggle.jpg" />
And what I want it to toggle is this:
<ul id="listview" data-filter="true">
So, basically I need to change from data-filter="true" or data-filter="false" and so on.
How can I get this working using JQuery?
$('#myToggleButton').click(function(){
var $listview = $('#listview');
$listview.attr('data-filter',
$listview.attr('data-filter')=='false' ? 'true' : 'false'
);
});
Something along the lines of ?
var $list = $('#listview');
$('#myToggleButton').click(function (event) {
if($list.data('filter') == true) {
$list.attr('data-filter', false);
}else {
$list.attr('data-filter', true);
}
});
Here's a more succinct and modern jQuery way using the data() method to handle data attributes:
$('#myToggleButton').click(function (){
var listview = $('#listview');
listview.data('filter', !listview.data('filter'));
listview.listview('refresh');
});​
Here's a JSFiddle as well so you can see it in action.

Locating Hidden Field Using JQuery

Boiled down to the barest element, I just want to set a hidden field's value when I click an element on the page.
HTML:
<div id="toggleParent">
<input type="hidden" name="toggleValue" id="toggleValue" value="closed" />
<h2>Click Me</h2>
</div>
jQuery:
jQuery(document).ready(function() {
var toggle;
jQuery('div#toggleParent h2').click(function () {
if (toggle == '' || toggle == 'open') {
toggle = 'closed';
} else {
toggle = 'open';
}
jQuery('div#toggleParent input#toggleValue').val(toggle);
});
});
Obviously, it's not working. (Why would I be here otherwise?) The click event is working fine, as I can step through it in Firebug. But when it gets to setting the value, the code fails. What's more, trying alert(jQuery('div#toggleParent input#toggleValue').length) returns 0. In fact, alert(jQuery('div#toggleParent h2').length) returns 0 even though the click event on that exact element just fired!
What am I missing?
This:
document.ready(function () {...});
Should be:
jQuery(document).ready(function () {...});
Or even:
jQuery(function () {...});
Or...
jQuery(function ($) { /* Use $ in here instead of jQuery */ });
Keep in mind that when using IDs, any other selector is unnecessary since IDs are unique. This is sufficient:
jQuery('#toggleValue').val(toggle);
Your 'toggle' value is undefined, you only define it in document.ready, but do not assign any value to it. To assign, use
var toggle = jQuery('div#toggleParent input#toggleValue').val();
I propose this code:
jQuery(function($) {
var toggleParent = $('#toggleParent')[0],
toggleValue = $('#toggleValue')[0];
$(toggleParent).find('h2').click(function() {
toggleValue.value = toggleValue.value === 'closed' ? 'open' : 'closed';
});
});
Try this code:
$(document).ready(function() {
var toggle;
$('div#toggleParent h2').click(function() {
if (toggle == '' || toggle == 'open') {
toggle = 'closed';
} else {
toggle = 'open';
}
$('div#toggleParent input#toggleValue').val(toggle);
alert($("input#toggleValue").val()); // check what the new value is
});
});

Categories

Resources