toggle switch ngclass onclick with angularjs - javascript

I want to change the class of a button when it clicked and also reverse back to its former state when its click again
$scope.like_btn = "icon ion-ios-heart";
$scope.like_btn2 = "icon ion-ios-heart assertive";
$scope.likepic=function() {
event.preventDefault();
if ($scope.like_btn === "icon ion-ios-heart"){
$scope.like_btn = "icon ion-ios-heart assertive";
$http.post("http://localhost/mywork/scripts/like.php",
{'u_pic_id':$scope.u_pic_id})
.success(function(data){
console.log(data)
});
}
else {
$scope.like_btn = "icon ion-ios-heart assertive";
$scope.like_btn = "icon ion-ios-heart";
$http.post("http://localhost/mywork/scripts/like_delete.php",
{'u_pic_id':$scope.u_pic_id})
.success(function(data){
console.log(data)
});
}
}
HTML
Click to like
<i ng-class="{ '{{like_btn}}': item.answer==='no liked','{{like_btn2}}':item.answer=='liked' }" ></i> {{item.love_total}} Likes

Your 'item' is probably not getting updated after the service succeeded.
So one way is to add following to the controller:
$scope.item.isLiked = false; // or initiase it with item.isLiked
$scope.likepic=function(item) {
item.isLiked = item.isLiked;
...
...
}
Change your angular expression to the following :
<i ng-click="likepic(item)" ng-class="{ '{{like_btn}}': item.answer=='no liked','{{like_btn2}}': item.answer=='liked' }" ></i>
You need to update the varible names little bit.

As I look at your case, the only change with onclick is that you are adding 'assertive' class. Below would be the approach.
Changes in the HTML View:
Click to like
<i class="icon ion-ios-heart" ng-class="{'assertive': liked}" ></i> {{item.love_total}} Likes
Changes in Javascript
// Initialize the flag here
$scope.liked = false;
$scope.likepic = function() {
event.preventDefault();
// Toggle the flag here
$scope.liked = !$scope.liked;
// Then perform task as per the new value
// There is some possibility of optimization below too. But since that is not the question, no changes are done here
if ($scope.liked) {
$http.post("http://localhost/mywork/scripts/like.php", { 'u_pic_id': $scope.u_pic_id })
.success(function(data) {
console.log(data)
});
} else {
$http.post("http://localhost/mywork/scripts/like_delete.php", { 'u_pic_id': $scope.u_pic_id })
.success(function(data) {
console.log(data)
});
}
}

Related

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}"

toggle mute and unmute with javascript

I'm trying to create a button for muting and un-mute.
Initially I have by button set up like this:
<i class="fa fa-microphone" id="audio"></i>
and what I want is that when you click it, the class becomes:
<i class="fa fa-microphone-slash" id="audio"></i>
now I have my javascript set up like this:
$(document).ready(function() {
$('#audio').click(function() {
publisher.publishAudio(false);
});
});
which essentially mutes it, now I need to make it so that it can also unmute when I click on the button
you can check if the publisher is sending video/audio on the stream it self like this:
publisher.stream.hasAudio
publisher.stream.hasVideo
then you can use the ! (bang) to invert it
publisher.publishAudio(!publisher.stream.hasAudio);
publisher.publishVideo(!publisher.stream.hasVideo);
so to toggle the class aswell you do someting like
$(document).ready(function() {
var toggleAudioBtn = $('#audio')
toggleAudioBtn.click(function() {
toggleAudioBtn.toggleClass("fa-microphone-slash").toggleClass("fa-microphone");
publisher.publishAudio(!publisher.stream.hasAudio);
});
});
I don't know jquery that well but here's some simple javascript code to manipulate the class
$(document).ready(function() {
$('#audio').click(function() {
var audio = document.querySelector("#audio");
// get current class state
var currentState = audio.getAttribute("class");
// change class
if(currentState === "fa fa-microphone"){
audio.setAttribute("class", "fa fa-microphone-slash");
}else{
audio.setAttribute("class", "fa fa-microphone");
}
});
});
Using jQuery, I'd chain toggleClass, along with an if statement using hasClass for the logic:
$(document).ready(function() {
$('#audio').click(function() {
if ($(this).hasClass("fa-microphone-slash")) {
publisher.publishAudio(true);
} else {
publisher.publishAudio(false);
}
$(this).toggleClass("fa-microphone-slash");
$(this).toggleClass("fa-microphone");
publisher.publishAudio($(this).hasClass(""));
});
});
If you want a DRY solution with no if statement, based on the class:
$(document).ready(function() {
$('#audio').click(function() {
publisher.publishAudio($(this).hasClass("fa-microphone-slash"));
$(this).toggleClass("fa-microphone-slash");
$(this).toggleClass("fa-microphone");
});
});
The second solution will just use the presence of the fa-microphone tag as a boolean for whether to perform a mute.

How to trigger a function from a object

I want to get the console.log to output true or false on click of .icons div.
Here is some live code: codepen
I have a model called navigation
$scope.navigation = {
status: false;
}
And a big object that will toggle the ui
$scope.toggle = {
menu: function() {
$scope.navigation.status = !$scope.navigation.status;
alert($scope.navigation.status);
}
};
The trigger is an ng-click="open.menu()" :
<div class="icons " ng-repeat="(key, val) in squares" ng-style="perspective" ng-click="toggle.menu()">
Try:
toggle.menu()
instead of
open.menu()

how to create up/down voting function in angularjs

Hey guys may i know how can i create a up/down voting function in angularjs ? i want to make it to something similar to stackoverflow or reddit.
i found a Jquery plugin https://github.com/janosgyerik/jquery-upvote that does what i want but its in Jquery.
i have tried several approach to do it but i still can't get it works well. here's my approach.
HTML
<a class="green" ng-click="isUpVoted = !isUpVoted" ng-style="afterVoteUp" href=""> <i title="Up Votes" class="fa fa-arrow-circle-up fa-2x"></i></a>
<a class="maroon" ng-click="isDownVoted = !isDownVoted" ng-style="afterVoteDown" href="" > <i title="Down Votes" class="fa fa-arrow-circle-down fa-2x "></i></a>
Controller
$scope.isUpVoted = false;
$scope.$watch("isUpVoted",function(newVal, oldVal){
if(newVal != oldVal){
if(newVal){
// first click
// upvote
}else{
// second click
// remove upvote
}
}
});
$scope.isDownVoted = false;
$scope.$watch("isDownVoted",function(newVal, oldVal){
if(newVal != oldVal){
if(newVal){
// first click
// downvote
}else{
// second click
// remove downvote
}
}
});
which work completely fine for one button, however i still can't figure out how to make this 2 buttons work together, for example when user click upvote downvote will cancel or vice versa and click the upvote again to cancel vote.
Just use a single scope variable to act like a toggle button.
Sample Demo: http://plnkr.co/edit/C4w9hDK3xW1R0ua3WPgU?p=preview
HTML:
<body ng-controller="MainCtrl">
<i title="Up Votes" ng-click="changeVote(vote, 'up')" class="fa fa-arrow-circle-up fa-2x" ng-class="{true:'up', false:''}[vote=='up']"></i>
<br>
<i title="Down Votes" ng-click="changeVote(vote, 'down')" class="fa fa-arrow-circle-down fa-2x" ng-class="{true:'down', false:''}[vote=='down']"></i>
<br>Vote: {{vote}}
Controller Logic:
app.controller('MainCtrl', function($scope) {
$scope.changeVote = function(vote, flag) {
$scope.vote = vote == flag ? 'None' : flag;
alert($scope.vote);
};
});
It should be simple to make something like this.
Here's a simple example:
JS:
var app = angular.module('voteApp', []);
app.controller('MainCtrl', function ($scope) {
$scope.upVote = function () {
$scope.vote++;
}
$scope.downVote = function () {
$scope.vote--;
}
$scope.vote = 0;
});
Fiddle.

How ot give $this in Angular js

I am displaying datas in a grid ,on click of active or inactive button i have to change the button ,functionality is working fine ,for changing icon i am unable to find the active clicked button ,in jquery we can use "this" ,but no idea in angular js ,pls help
$scope.activeSource = function(datasource,status)
{
$scope.loading = true;
$scope.activeInfo = {
datasource:datasource,
};
$scope.alerts = [];
if(status == "Stopped")
{
$scope.entityService.activeInfo($scope.activeInfo,
function( msg ) // success
{
$scope.loading = false;
$rootScope.successMsg.push(msg);
$('.icon-play').hide(); // this.
$('.icon-stop').show(); // this. no idea
},
function( msg ) // error
{
$scope.loading = false;
$rootScope.successMsg.push(msg);
}
);
You don't need to use this to access the button. Instead, in your controller create a javascript object that holds all the attributes for the button. Something like this:
$scope.myButton = {
src : 'foobar.png',
isVisible : true
};
Then, define your button like this:
<img ng-src="myButton.src" ng-show="myButton.isVisible" />
Now, when you want to modify any attribute of the button, you just need to change the javascript object myButton, and angular will take care of updating the actual button.
For example, if you want to hide the button:
// you don't need to do this
// $('#myButton').hide();
// instead just do this
$scope.myButton.isVisible = false;
Similarly, you can change the src of the image as well.

Categories

Resources