Move div with keys - javascript

I have to create a little program in AngularJS for my school, but I'm not very advanced yet, because I lack basic training.
I tried to make a texture move using arrow keys, but I didn't have any success finding a usable answer on the Internet.
I'd be happy if anyone would help me.
Here is the code I use for now to move it, if that helps:
<!DOCTYPE html>
<html>
<head>
<title>Angular Game</title>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body bgcolor="#151B54">
<div ng-app="myApp" ng-controller="myCtrl">
<div id="myDiv" ng-style=" {'position':'relative','height':'20px','width':'92px','background-color':'#348781','left': divleft+'px','top':divtop+'px'}">Raumschiff</div>
<input type="button" ng-mousedown="goLeft()" value="<"> <input type="button" ng-mousedown="goRight()" value=">"><br>
<input type="button" ng-mousedown="goDown()" value="v"> <input type="button" ng-mousedown="goUp()" value="^">
<input type="button" ng-click="startInterval()" value="start">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$interval) {
$scope.divleft = 200;
$scope.divtop = 300;
$scope.goRight = function ()
{
$scope.divvel2 +=1;
}
$scope.goLeft = function ()
{
$scope.divvel2 -=1;
}
$scope.goUp = function ()
{
$scope.divvel +=1;
}
$scope.goDown = function ()
{
$scope.divvel -=1;
}
$scope.moveDiv = true;
var intervalHandler;
$scope.divvel ="0";
$scope.divvel2 ="0";
$scope.startInterval = function ()
{
$interval.cancel(intervalHandler);
intervalHandler = $interval(myIntervalFunction,50);
}
myIntervalFunction = function()
{
$scope.divtop-=parseInt($scope.divvel);
$scope.divleft+=parseInt($scope.divvel2);
}
});
</script>
</body>
</html>

To make a texture move using arrow keys. Try this
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$interval) {
$scope.divleft = 100;
$scope.divtop = 30;
$scope.goRight = function ()
{
$scope.divleft +=1;
}
$scope.goLeft = function ()
{
$scope.divleft -=1;
}
$scope.goUp = function ()
{
$scope.divtop -=1;
}
$scope.goDown = function ()
{
$scope.divtop +=1;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div id="myDiv" ng-style=" {'position':'relative','height':'20px','width':'92px','background-color':'#348781','left': divleft+'px','top':divtop+'px'}">Raumschiff</div>
<input type="button" ng-mousedown="goLeft()" value="<"> <input type="button" ng-mousedown="goRight()" value=">"><br>
<input type="button" ng-mousedown="goDown()" value="v"> <input type="button" ng-mousedown="goUp()" value="^">
</div>

Angular has directives that will allow you to easily listen for key events.
I think ng-keyup should work fine for you.
You will need to add the ng-keyup directive to the body tag to make sure you listen for key events at the highest level. You will also have to move your ng-app and ng-controller directives to the body tag too so that the function that you declare for your key events is in the correct scope.
So change
<body bgcolor="#151B54">
<div ng-app="myApp" ng-controller="myCtrl">
to
<body bgcolor="#151B54" ng-app="myApp" ng-controller="myCtrl" ng-keyup="handleKeyup($event)">
<div>
You will then be able to do something with those events in your controller.
So add this to your controller:
$scope.handleKeyup = function (e) {
switch (e.which) {
case 37:
$scope.goLeft();
break;
case 38:
$scope.goUp();
break;
case 39:
$scope.goRight();
break;
case 40:
$scope.goDown();
break;
}
};

Related

Elements within dynamically created of <div> on each button click is not properly overridden

I am trying to create a comment box where on each submit a new is dynamically created. The inner elements of the <div> being 3 buttons Edit, Post, Cancel and a close icon(image). These are also dynamically created. I finally append them all together. The below code would generate something like the below image on two submits. The error I'm facing is that, whatever <div>'s close icon/button is clicked, always the last <div> is being affected. Here I tried to close 'Hi' but 'hello' is being affected.Also there is a duplication of the <div> on even comments.
Kindly help me correct these issues.
<!DOCTYPE html>
<html>
<head>
<title>Comment</title>
</head>
<body>
<textarea id="ta" rows="30" cols="30" readonly></textarea>
<br>
<input type="textbox" id="tb"></input><br>
<button onclick="add()">Submit</button><br>
<script type="text/javascript">
var newDiv="",i=1,ta="";
function add() {
i++;
ta=document.getElementById('ta');
newDiv = document.createElement("div");
newDiv.id = "d"+i;
newDiv.style.display="block";
newTa = document.createElement("input");
newTa.type="text"
newTa.id = "t"+i;
//newTa.readonly='true';
newTa.setAttribute("readOnly","true");
newTa.style.display="block";
newTa.onclick=function(){
newP.style.visibility="visible";
newImg.style.visibility="visible";
newBut1.style.visibility="visible";
newButt1.style.visibility="visible";
};
// document.querySelector('body').addEventListener('click', function(event) {
newP=document.createElement("BUTTON");
newP.id="p"+i;
newP.innerHTML="Edit";
newP.style.visibility="hidden";
newP.style.display="inline";
newP.onclick=function()
{
newTa.removeAttribute('readonly'); // only needed the first time
newTa.readOnly = false;
//newTa.setAttribute("readOnly","false");
//newTa.readonly='false';
//newP.innerHTML="wrng";
}
newImg=document.createElement("IMG");
newImg.id="i"+i;
newImg.src="http://www.freeiconspng.com/uploads/close-icon-30.png";
newImg.style.width="20%";
newImg.style.height="20%";
newImg.alt="close";
newImg.style.visibility="hidden";
newImg.style.display="inline";
newImg.onclick=function()
{
newDiv.innerHTML="";
//newDiv.remove();
}
newBut1=document.createElement("button");
newBut1.id="b"+i;
newBut1.innerHTML="Post";
newBut1.style.visibility="hidden";
newBut1.style.display="inline";
newBut1.onclick=function(){
//newTa.readonly='true';
newTa.setAttribute("readOnly","true");
}
newButt1=document.createElement("button");
newButt1.id="bt"+i;
newButt1.innerHTML="Cancel";
newButt1.style.visibility="hidden";
newButt1.onclick=function(){
newTa.value=document.getElementById('tb').value;
newTa.readonly='true';
}
newDiv.appendChild(newTa);
newDiv.appendChild(newP);
newDiv.appendChild(newImg);
newDiv.appendChild(newBut1);
newDiv.appendChild(newButt1);
var b=""
b="t"+i;
ta.appendChild(newDiv);
document.getElementById(b).value=document.getElementById('tb').value;
}
</script>
</body>
</html>
Try this code. I have changed textarea to div.
Initial i to 0 instead of 1. You can also set it to 1. It won't affect the functionality.
Some variables were global, I have changed them to local variable now like newDiv,newP, newImg etc.
<!DOCTYPE html>
<html>
<head>
<title>Comment</title>
</head>
<body>
<!--<textarea id="ta" rows="30" cols="30" readonly></textarea>-->
<div id="ta"></div>
<br>
<input type="textbox" id="tb"></input><br>
<button onclick="add()">Submit</button><br>
<script type="text/javascript">
var i=0,ta="";
function add() {
(function(){
i++;
var temp_i = i;
ta=document.getElementById('ta');
var newDiv = document.createElement("div");
newDiv.id = "d"+temp_i;
newDiv.style.display="block";
newTa = document.createElement("input");
newTa.type="text"
newTa.id = "t"+temp_i;
//newTa.readonly='true';
newTa.setAttribute("readOnly","true");
newTa.style.display="block";
newTa.onclick=function(){
console.log(temp_i);
console.log(i);
newP.style.visibility="visible";
newImg.style.visibility="visible";
newBut1.style.visibility="visible";
newButt1.style.visibility="visible";
};
// document.querySelector('body').addEventListener('click', function(event) {
var newP=document.createElement("BUTTON");
newP.id="p"+temp_i;
newP.innerHTML="Edit";
newP.style.visibility="hidden";
newP.style.display="inline";
newP.onclick=function()
{
newTa.removeAttribute('readonly'); // only needed the first time
newTa.readOnly = false;
//newTa.setAttribute("readOnly","false");
//newTa.readonly='false';
//newP.innerHTML="wrng";
}
var newImg=document.createElement("IMG");
newImg.id="i"+temp_i;
newImg.src="http://www.freeiconspng.com/uploads/close-icon-30.png";
newImg.style.width="20%";
newImg.style.height="20%";
newImg.alt="close";
newImg.style.visibility="hidden";
newImg.style.display="inline";
newImg.onclick=function()
{
newDiv.innerHTML="";
//newDiv.remove();
}
var newBut1=document.createElement("button");
newBut1.id="b"+temp_i;
newBut1.innerHTML="Post";
newBut1.style.visibility="hidden";
newBut1.style.display="inline";
newBut1.onclick=function(){
//newTa.readonly='true';
newTa.setAttribute("readOnly","true");
}
var newButt1=document.createElement("button");
newButt1.id="bt"+temp_i;
newButt1.innerHTML="Cancel";
newButt1.style.visibility="hidden";
newButt1.onclick=function(){
newTa.value=document.getElementById('tb').value;
newTa.readonly='true';
}
newDiv.appendChild(newTa);
newDiv.appendChild(newP);
newDiv.appendChild(newImg);
newDiv.appendChild(newBut1);
newDiv.appendChild(newButt1);
var b=""
b="t"+temp_i;
ta.appendChild(newDiv);
document.getElementById(b).value=document.getElementById('tb').value;
})();
}
</script>
</body>
</html>
Why not you use jquery to minimize your code campaign. Below is the code which will fix your problem.
<!DOCTYPE html>
<html>
<head>
<title>Comment</title>
</head>
<body>
<br>
<div class="container">
<input type="textbox" id="tb"><br>
<button>Edit</button><button>Post</button><button class="cancel">Cancel</button><br />
</div>
<button class="submit">Submit</button><br>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.submit').click(function() {
var element = '<div class="container">'+'<input type="textbox" id="tb"><br>'+
'<button>Edit</button><button>Post</button><button class="cancel">Cancel</button><br /></div>';
$('.submit').before(element);
});
$('body').delegate('.cancel', 'click', function() {
$(this).parent().remove();
});
});
</script>
</body>
</html>
Thanks

Problems with calling a function in the HTML file using Angular JS

I am fairly new with AngularJS. I'm trying to do something simple for the moment. I created a table with some text I'll have to search with, a reset button (In my program is called "Pulisci") and some panels I'll have to use later. The problem is that, if I call the function I created for resetting the page, the panels mysteriously stop working. I'm banging my head on this since last week.
HTML
<!DOCTYPE html>
<html ng-app="sbi">
<head>
<link rel="stylesheet" type="text/css" href="bootstrap.min.css">
<style>
table,
td {
border-width: 2px;
border-collapse: collapse;
padding: 15px;
color: #000000;
text-align: center;
}
table.pos_fixed1 {
position: relative;
top: 30px;
left: 10px;
}
</style>
</head>
<body>
<form name="form">
<table summary="" width="10%" class="pos_fixed1" align="center">
<tr>
<td>Code Subinstaller<br><input name="codeSub" type="text" ng-model="codeSub"></td>
<td>Stato<br>
<select>
<option value="1">...</option>
<option value="2">WHITE LIST</option>
<option value="3">GRAY LIST</option>
</select>
</td>
</tr>
<tr>
<td>Nome Sub Installer<input name="nomeSub" type="text" ng-model="nomeSub"></td>
<td>Cognome Sub Installer<input name="cognSub" type="text" ng-model="cognSub"></td>
<td>Codice Fiscale<input name="codFisc" type="text" ng- model="codFisc"> </td>
</tr>
</table><br>
<button class="btn btn-wide btn-default.active.focus" data-ng- click="">Cerca</button>
<button class="btn btn-wide btn-default.active.focus" data-ng- click="reset()">Pulisci</button>
</form><br><br>
<section ng-controller="PanelController as panel">
<ul class="nav nav-pills">
<li ng-class="{ active:panel.isSelected(1) }"> <a href ng- click="panel.selectTab(1)">Description</a></li>
<li ng-class="{ active:panel.isSelected(2) }"> <a href ng- click="panel.selectTab(2)">Specifications</a></li>
<li ng-class="{ active:panel.isSelected(3) }"> <a href ng- click="panel.selectTab(3)">Reviews</a></li>
</ul>
<div class="panel" ng-show="panel.isSelected(1)">
<h4>Description </h4>
<p>wtf</p>
</div>
<div class="panel" ng-show="panel.isSelected(2)">
<h4>Idk</h4>
<p>Idc</p>
</div>
<div class="panel" ng-show="panel.isSelected(3)">
<h4>APPARI</h4>
<p>???</p>
</div>
</section>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="myapp.js"></script>
</body>
</html>
JS
(function() {
var app = angular.module('sbi', []);
app.controller('PanelController', function() {
this.tab = 1;
this.selectTab = function(setTab) {
this.tab = setTab;
};
this.isSelected = function(checkTab) {
return this.tab === checkTab;
};
});
})();
(function($scope) {
var app = angular.module('sbi', []);
function MyCtrl($scope) {
$scope.reset = function() {
$scope.requiredField = '';
};
};
});
How can I make the Reset() and the panels work simultaneously?
You have re-initialized your angular module.
Initializing your angular module
var app = angular.module('sbi', []);
Second argument in angular.module() is for injecting the required dependency for the module. And hence should be done only once.
In your code, you have again initialized your module.
(function () {
//initialization
var app = angular.module('sbi', []);
app.controller('PanelController', function () {
this.tab = 1;
this.selectTab = function (setTab) {
this.tab = setTab;
};
this.isSelected = function (checkTab) {
return this.tab === checkTab;
};
});
})();
(function ($scope) {
//edit in your code
//re-using the already initialized module
var app = angular.module('sbi');
function MyCtrl($scope) {
$scope.reset = function () {
$scope.requiredField = '';
};
};
});
You should not pass the second argument as parameter.
Reusing your angular module
var app = angular.module('sbi');
EDIT :
Try the following code :
(function () {
var app = angular.module('sbi', []);
app.controller('PanelController', ['$scope', function($scope) {
$scope.tab = 1;
$scope.selectTab = function (setTab) {
$scope.tab = setTab;
};
$scope.isSelected = function (checkTab) {
return $scope.tab === checkTab;
};
$scope.reset = function () {
$scope.requiredField = '';
};
}]);
})();
There is something you are clearly missing here: your reset function is attached to... nothing.
The MyCtrl function is never called (from what we've seen), and the $scope variable is not injected the Angular-way. Actually, nothing here is in the Angular way. Let me try to adjust this so you understand what you should aim for.
First of all, as #Akshay mentioned, there is a huge difference between angular.module('something', []) and angular.module('something'), but they already pointed that out in their response.
Then, your MyCtrl hasn't been registered as a controller in Angular. You just defined the function, you were missing these lines:
var app = angular.module('sbi');
function MyCtrl($scope) {
$scope.reset = function () {
$scope.requiredField = '';
};
};
// This controller will be known as 'MyCtrl'
app.controller('MyCtrl', MyCtrl);
This should work. Note that you won't be needing the surrounding (function ($scope) {...}) as it won't be executed correctly.
Then, you will have to tell Angular to use that controller in that specific part of your page:
<!-- Adding the ng-controller directive here -->
<form name="form" ng-controller="MyCtrl">
...
<button class="btn btn-wide btn-default.active.focus" data-ng-click="reset()">Pulisci</button>
</form>
Then, you will be able to handle your requiredField variable as you wish.

Button onclick doesn't change style.display of div

I have two divs, called loginpending and loggedin, which I am trying to configure so that once a button (button) is clicked, the divs will "flicker" between one being on and one being off.
For example, in this current state (with loginpending's display as block and loggedin's display as none), once the button is clicked, loginpending's display will become none and loggedin's display will become block through the function loginUpdate, which is then called through launch depending on what the state of each div is.
However, it doesn't work - the state of the buttons don't change at all once the button is clicked.
Help!
HTML code:
<div id="loginpending" style="display:block;">
Signup/Login here!
</div>
<div id="loggedin" style="display:none;">
Hello!
</div>
<button id="button" onclick="launch()">Hello!</button>
Javascript code (with Jquery):
var logincheck = 0;
function loginUpdate() {
"use strict";
$("#loginpending").toggle();
$("#loggedin").toggle();
}
function launch() {
"use strict";
var loginpending = document.getElementById("loginpending").style.display;
var loggedin = document.getElementById("loggedin").style.display;
window.alert(loginpending);
window.alert(loggedin);
if (loginpending === "none") {
logincheck = 0;
loginUpdate();
} else if (loggedin === "none") {
logincheck = 1;
loginUpdate();
} else {
logincheck = 0;
$("#loggedin").toggle();
}
}
Right now your button is submitting the from which refreshes the page reloadsin its original state.
You need to set the type of button to type="button"
<button id="button" type="button" onclick="launch()">Hello!</button>
$(document).ready(function() {
$('button').on('click', function(){
$('div').toggleClass('hidden');
})
});
.hidden {
display: none;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="loginpending" class="">
Signup/Login here!
</div>
<div id="loggedin" class="hidden">
Hello!
</div>
<button id="button" onclick="">Hello!</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script type="text/javascript" src="sample.js"></script>
</body>
</html>
Code with jQuery
I tried to use your original code as much as I could.
var logincheck = 0;
$("#button").click(function() {
launch();
});
function loginUpdate() {
"use strict";
$("#loginpending").toggle();
$("#loggedin").toggle();
}
function launch() {
"use strict";
var loginpending = $("#loginpending").is(":hidden");
var loggedin = $("#loggedin").is(":hidden");
if(loginpending)
logincheck = 0;
else if (loggedin)
logincheck = 1
else
logincheck = 0;
loginUpdate();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="loginpending" style="display:block;">
Signup/Login here!
</div>
<div id="loggedin" style="display:none;">
Hello!
</div>
<button id="button" type="button">Hello!</button>
Gotta try this
$(function() {
var logincheck = 0;
function loginUpdate() {
"use strict";
$("#loginpending").toggle();
$("#loggedin").toggle();
}
$('#button').on('click', function(){
"use strict";
if(logincheck == 0) {
logincheck = 1;
}else{
logincheck = 0;
}
loginUpdate();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="loginpending" style="display:block;">
Signup/Login here!
</div>
<div id="loggedin" style="display:none;">
Hello!
</div>
<button id="button">Hello!</button>

Javascript event handler is not working

I am trying to to increment/decrement a value in a paragraph when a button is clicked.
$(document).ready(function() {
var breakTime = 5;
var section = 25;
var start = "Start";
var stop = "Stop";
function Pomodoro(element, target) {
this.element = element;
this.target = target;
};
Pomodoro.prototype.incrementer = function incrementer() {
// this takes care of break and section timers incrementing
this.element.click(function() {
breakTime++;
var el = this.target;
el.html(breakTime);
});
};
// end
Pomodoro.prototype.decrementer = function decrementer() {
// this takes care of break and section timers incrementing
breakerDec.element.click(function() {
breakTime--;
var el = breakerDec.target.html(breakTime);
});
};
// end
var breakerInc = new Pomodoro();
var ele = $("#inner1");
var tar = $("#par");
breakerInc.element = ele;
breakerInc.target = tar;
breakerInc.incrementer.bind(breakerInc);
//end
var breakerDec = new Pomodoro();
breakerDec.element = $("#inner2");
breakerDec.target = $("#par");
breakerDec.decrementer();
var sectionInc = new Pomodoro($("#inner3"), $("#par2"));
sectionInc.incrementer.bind(sectionInc);
});
and i am getting no result when i click the button.
this is the html:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pomodoro Timer</title><!-- End of Title -->
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="wrapper">
<div class="top">
<div class="div div-1"><p id="par" class="breaktime-1">5</p>
<div class="inner-div inner-1"><button id="inner1" type="button" class="btn">+</button></div>
<div class="inner-div inner-2"><button id="inner2" type="button" class="btn">-</button></div>
</div>
<div class="div div-2"><p id="par2" class="breaktime">25</p>
<div class="inner-div inner-1"><button id="inner3" type="button" class="btn">+</button></div>
<div class="inner-div inner-2"><button id="inner4" type="button" class="btn">-</button></div>
</div>
</div>
<div class="div div-3">
<h3 class="heading">section</h3>
<button type="button" class="btn-Start-Stop"></button
</div>
<div><p></p></div>
</div>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
Here is one (trimmed-down) solution just using vanilla javascript:
function changeValue() {
var breaktime = this.parentNode.getElementsByClassName('breaktime')[0];
var val = breaktime.innerHTML;
if (this.className === 'increment') {
val++;
}
else if (this.className === 'decrement') {
val--;
}
breaktime.innerHTML = val;
}
function startStop() {
var values = [];
var breaktimes = document.getElementsByClassName('breaktime');
breaktimes[1].classList.toggle('decrementing');
if (breaktimes[1].classList.contains('decrementing') === true) {
values[1] = parseInt(breaktimes[1].innerHTML);
values[1]--;
breaktimes[1].innerHTML = values[1];
var decrementer = setInterval(function(){
values[0] = parseInt(breaktimes[0].innerHTML);
values[1] = parseInt(breaktimes[1].innerHTML);
if (breaktimes[1].classList.contains('decrementing') !== true) {
clearInterval(decrementer);
}
values[1]--;
breaktimes[1].innerHTML = values[1];
if (values[1] === values[0]) {
window.alert('The counter has reached ' + values[1]);
clearInterval(decrementer);
}
}, 1000);
}
}
var buttons = document.getElementsByTagName('button');
var startStopButton = buttons[(buttons.length -1)];
for (var i = 0; (i+1) < buttons.length; i++) {
buttons[i].addEventListener('click',changeValue,false);
}
startStopButton.addEventListener('click',startStop,false);
<section>
<div>
<p class="breaktime">5</p>
<button id="inner1" type="button" class="increment">+</button>
<button id="inner2" type="button" class="decrement">-</button>
</div>
<div>
<p class="breaktime">25</p>
<button id="inner3" type="button" class="increment">+</button>
<button id="inner4" type="button" class="decrement">-</button>
</div>
<div>
<h3>Section</h3>
<button type="button" class="btn-Start-Stop">Start / Stop</button>
</div>
<div>
<p></p>
</div>
</section>
If you'd like to implement logic using constructors, you can bind events inside of initialization of your instance.
Here is reworked your code based on your html. But code could be improved, so Pomodoro instance can be able not only to decrease or increase, but do both functions.
Also some template engine can give you ability to easy define amount of increase/decrease blocks you want to add to your page.

Using one function with different variables

Try to create two controllers with a same logic. when I use separate functions for each var it works. But when I try to pass var as parameter it does nothing.
Code here:
function Ctrl($scope) {
$scope.Score1 = 0;
$scope.Score2 = 0;
$scope.add_btn = function(num) {
$scope.num ++;
};
$scope.dist_btn = function(num) {
if ($scope.num > 0) {
$scope.num --;
} else {
$scope.num = 0;
}
};
}
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ -->
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<style>
<div ng-app>
<div ng-controller="Ctrl">
<button ng-click="add_btn(Score1)">+</button>
<input type="text" value="{{Score1}}">
<button ng-click="dist_btn(Score1)">-</button>
<button ng-click="add_btn(Score2">+</button>
<input type="text" value="{{Score2}}">
<button ng-click="dist_btn(Score2)">-</button>
</div>
</div>
You can use this logic without useing any array, you used $scope.num but it creates a new variable on the scope so fails. this would work properly
function Ctrl($scope) {
$scope.Score1 = 0;
$scope.Score2 = 0;
$scope.add_btn = function(num,from) {
num ++;
if(from == 1)
$scope.Score1 = num;
else
$scope.Score2 = num;
};
$scope.dist_btn = function(num,from ) {
if (num > 0) {
num --;
} else {
num = 0;
}
if(from == 1)
$scope.Score1 = num;
else
$scope.Score2 = num;
};
}
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ -->
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<style>
<div ng-app>
<div ng-controller="Ctrl">
<button ng-click="add_btn(Score1,1)">+</button>
<input type="text" value="{{Score1}}">
<button ng-click="dist_btn(Score1,1)">-</button>
<button ng-click="add_btn(Score2,2)">+</button>
<input type="text" value="{{Score2}}">
<button ng-click="dist_btn(Score2,2)">-</button>
</div>
</div>
Simple and dirty solution :)
There could be something better
function Ctrl($scope) {
$scope.Score = [0, 0];
$scope.add_btn = function(num) {
$scope.Score[num]++;
};
$scope.dist_btn = function(num) {
if ($scope.Score[num] > 0) {
$scope.Score[num]--;
} else {
num = 0;
}
};
}
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ -->
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<style>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<div ng-app>
<div ng-controller="Ctrl">
<button ng-click="add_btn(0)">+</button>
<input type="text" value="{{Score[0]}}">
<button ng-click="dist_btn(0)">-</button>
<button ng-click="add_btn(1)">+</button>
<input type="text" value="{{Score[1]}}">
<button ng-click="dist_btn(1)">-</button>
</div>
</div>
$scope.num // find num inside #scope
$scope[num] // find the member inside scope variable with the value of num (Score1 in your case)
also send the parameter from the element like this:
<button ng-click="add_btn('Score1')">+</button>
and instead num please refactor to id or something.. in short:
$scope.add_btn = function(id)
{
$scope[id]++;
};

Categories