Basic JavaScript button interaction - javascript

I'm new to JavaScript and Node.js.
I'm trying to get a button in my webpage to call a method in my controller when clicked, but so far I'm getting no response from my controller.
How do I call the .submitEntry() function from my button?
Here's the index.html file:
<!DOCTYPE html>
<meta charset="UTF-8">
<html ng-app='app'>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
<div ng-controller='GameController' class='container'>
<h1>Palindrome Game</h1>
<h2>Submit a new word!</h2>
<form role='form'>
<div class='form-group'>
<input ng-model="name" class='form-control' placeholder="Your name">
<input ng-model="word" class='form-control' placeholder="Word">
<button ng-click='submitEntry()' class='btn btn-default'>Submit word</button>
</div>
</form>
<h2>Top Scores</h2>
<ul class='list-group'>
<li ng-repeat="score in scores | orderBy:'-points'" class='list-group-item'>
<strong>{{score.name}}</strong> {{score.points}} points
</li>
</ul>
</div>
<script src='http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.4/angular.js'></script>
<script src='ng/app.js'></script>
</body>
And here's the app.js file:
var app = angular.module('app', []);
const button = document.getElementById('myButton');
button.addEventListener('click', function(e)
{
console.log('button was clicked');
});
app.controller('GameController', function($scope, GameService)
{
console.log("Debug 0");
$scope.submitEntry = function()
{
if (typeof $scope.name === 'undefined' || typeof $scope.word === 'undefined')
{
return;
}
var entry = {
name: $scope.name,
word: $scope.word
};
GameService.submitEntry(entry).success(function(points)
{
$scope.word = undefined;
GameService.getScores().success(function(scores)
{
$scope.scores = scores;
});
});
};
GameService.getScores().success(function(scores)
{
$scope.scores = scores;
});
});
app.service('GameService', function($http)
{
this.getScores = function() {
return $http.get('/api/getScores');
};
this.submitEntry = function(entry) {
return $http.post('/api/submitEntry', entry);
};
});
Thank you very much! Any help that could point me in the right direction will be very appreciated.

Here's a simple button that displays an alert once clicked.
function Channels($scope) {
$scope.test = function() {
alert('button clicked!')
}
}
angular.module('app', [])
.controller('Channels', Channels);
angular.bootstrap(document.body, ['app']);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<body ng-controller="Channels">
<button ng-click="test()">
test
</button>
</body>

Related

Not able to attach variables and functions with angularJS controller

when i am using $scope object to bind function and variable,and making changes accordingly in HTML the code is working fine ,but not with this object.
var app = angular.module("myApp", []);
app.controller("myCtrl", myCtrl);
function myCtrl()
{
console.log("registering app");
this.valueOne="0";
this.valueTwo="0";
this.result="0";
this.add=function () {
console.log("in add");
this.result=parseFloat(this.valueOne)+parseFloat(his.valueTwo);
valueOne="";
valueTwo="";
}
this.subtract=function () {
this.result=parseFloat(this.valueOne)-parseFloat(his.valueTwo)
valueOne="";
valueTwo="";
}
this.multiply=function() {
this.result=parseFloat(this.valueOne)*parseFloat(his.valueTwo)
valueOne="";
valueTwo="";
}
this.divide=function() {
this.result=parseFloat(this.valueOne)/parseFloat(his.valueTwo)
valueOne="";
valueTwo="";
}
}
<!DOCTYPE html>
<html lang="en-US">
<script src="angular.js"></script>
<script src="app.js"></script>
<body>
<div ng-app="myApp" >
<div ng-controller="myCtrl">
<p>Value 1 : <input type="text" ng-model="myCtrl.valueOne" placeholder="Value 1"></br>
Value 2 : <input type="text" ng-model="myCtrl.valueTwo" placeholder="Value 2"></br>
<button ng-click="myCtrl.add()">Add</button>
<button ng-click="myCtrl.subtract()">subtract</button>
<button ng-click="myCtrl.divide()">divide</button>
<button ng-click="myCtrl.multiply()">multiply</button>
</p>
<h1>Calculation Result {{myCtrl.result}}</h1>
</div>
</div>
</body>
</html>
And from where i am taking reference it is working fine there
var app = angular.module("calculatorApp", []);
app.controller("CalculatorCtrl", CalculatorCtrl);
function CalculatorCtrl() {
this.resultValue = 0;
this.buttonClicked = function(button) {
this.selectedOperation = button;
}
this.computeResult = function() {
var number1 = parseFloat(this.input1);
var number2 = parseFloat(this.input2);
if (this.selectedOperation === '+') {
this.resultValue = number1 + number2;
}
else if (this.selectedOperation === '-') {
this.resultValue = number1 - number2;
}
else if (this.selectedOperation === '*') {
this.resultValue = number1 * number2;
}
else if (this.selectedOperation === '/') {
this.resultValue = number1 / number2;
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="calculatorApp">
<head>
<title>Calculator App</title>
<script src='angular.js'></script>
<script src='app.js'></script>
</head>
<body>
<h1>Calculator App</h1>
<div ng-controller="CalculatorCtrl as ctrl">
<input type="text" ng-model="ctrl.input1"></input>
<span ng-bind="ctrl.selectedOperation"></span>
<input type="text" ng-model="ctrl.input2"></input>
<button ng-click="ctrl.computeResult()">=</button>
<span ng-bind="ctrl.resultValue"></span>
<p>
Choose operation:
<button ng-click="ctrl.buttonClicked('+')">+</button>
<button ng-click="ctrl.buttonClicked('-')">-</button>
<button ng-click="ctrl.buttonClicked('*')">*</button>
<button ng-click="ctrl.buttonClicked('/')">/</button>
</p>
</div>
</body>
</html>
Not able to get what i am doing wrong .
What you missed is a tiny detail:
In working code:
ng-controller="CalculatorCtrl as ctrl" it had this.
Where as, your code:
ng-controller="myCtrl" has this. It means your HTML code didn't have a reference of your controller.
You can just change it to ng-controller="myCtrl as myCtrl" and it should work fine!
Also, your code snippet was having occurances of his instead of this in controller methods. Fixed those. And following is your working snippet:
var app = angular.module("myApp", []);
app.controller("myCtrl", myCtrl);
function myCtrl()
{
console.log("registering app");
this.valueOne="0";
this.valueTwo="0";
this.result="0";
this.add=function () {
console.log("in add");
this.result=parseFloat(this.valueOne)+parseFloat(this.valueTwo);
valueOne="";
valueTwo="";
}
this.subtract=function () {
this.result=parseFloat(this.valueOne)-parseFloat(this.valueTwo)
valueOne="";
valueTwo="";
}
this.multiply=function() {
this.result=parseFloat(this.valueOne)*parseFloat(this.valueTwo)
valueOne="";
valueTwo="";
}
this.divide=function() {
this.result=parseFloat(this.valueOne)/parseFloat(this.valueTwo)
valueOne="";
valueTwo="";
}
}
<!DOCTYPE html>
<html lang="en-US">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>
<script src="app.js"></script>
<body>
<div ng-app="myApp" >
<div ng-controller="myCtrl as myCtrl">
<p>Value 1 : <input type="text" ng-model="myCtrl.valueOne" placeholder="Value 1"></br>
Value 2 : <input type="text" ng-model="myCtrl.valueTwo" placeholder="Value 2"></br>
<button ng-click="myCtrl.add()">Add</button>
<button ng-click="myCtrl.subtract()">subtract</button>
<button ng-click="myCtrl.divide()">divide</button>
<button ng-click="myCtrl.multiply()">multiply</button>
</p>
<h1>Calculation Result {{myCtrl.result}}</h1>
</div>
</div>
</body>
</html>

How to bind children value to model angularjs

In the below code data is not binding between label value to input model..
if we click on div it will shows the value of children label in input model, where i tried to change label name, but two way binding is not happening between them..
DEMO
// Code goes here
var app = angular.module('myapp', []);
app.controller('MainCtrl', function($scope) {
$scope.textVal = 'click on User Name';
$scope.selectedEvent = {};
$scope.setText = function (element) {
$scope.selectedEvent = element;
$scope.textVal = angular.element(element.currentTarget).children('label').html();
};
$scope.changeLabelText = function () {
$scope.selectedEvent.innerHTML = $scope.textVal;
angular.element(element.currentTarget).innerHTML = $scope.textVal;
};
});
<!DOCTYPE html>
<html ng-app='myapp'>
<head>
<script data-require="jquery#*" data-semver="2.1.4" src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script data-require="angular.js#1.4.8" data-semver="1.4.8" src="https://code.angularjs.org/1.4.8/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" >
<script src="script.js"></script>
</head>
<body ng-controller="MainCtrl">
<input type="text" ng-model="textVal" ng-change="changeLabelText($event)">//change user name here//
<div ng-click="setText($event)">
<label>User Name</label><br/>
<input type="text" placeholder="enter username">
</div>
</body>
</html>
Updated HTML...
<input type="text" ng-model="textVal" ng-change="changeLabelText($event)">//change user name here//
<div ng-click="setText($event)">
<label>User Name</label><br/>
<input type="text" placeholder="enter username">
</div>
Update JS
var app = angular.module('myapp', []);
app.controller('MainCtrl', function($scope) {
$scope.textVal = 'click on User Name';
$scope.selectedEvent = {};
$scope.setText = function (element) {
$scope.selectedEvent = element;
$scope.textVal = angular.element(element.currentTarget).children('label').html();
};
$scope.changeLabelText = function () {
// $scope.selectedEvent.innerHTML = $scope.textVal;
// angular.elhement(element.currentTarget).innerHTML = $scope.textVal;
angular.element($scope.selectedEvent.currentTarget).children('label').html($scope.textVal)
};
});
Updated code here...
var app = angular.module('myapp', []);
app.controller('MainCtrl', function($scope) {
$scope.textVal = 'click on User Name';
$scope.selectedEvent = {};
$scope.setText = function (element) {
$scope.selectedEvent = element;
$scope.textVal = angular.element(element.currentTarget).html();
};
$scope.changeLabelText = function () {
// $scope.selectedEvent.innerHTML = $scope.textVal;
//angular.element($scope.selectedEvent.currentTarget).html($scope.textVal);
// $scope.selectedEvent.currentTarget.innerHTML = $scope.textVal;
angular.element($scope.selectedEvent.currentTarget).children('label').html($scope.textVal)
};
});
HTML Updated...
<body ng-controller="MainCtrl">
<input type="text" ng-model="textVal" ng-change="changeLabelText($event)">//change user name here//
<div ng-click="setText($event)">
<label >User Name</label><br/>
<input type="text" placeholder="enter username">
</div>
</body>
Use the angular ng-model
var app = angular.module('myapp', []);
app.controller('MainCtrl', function($scope) {
$scope.textVal = 'click on User Name';
$scope.setText = function (element) {
$scope.textVal = 'click on User Name';
$scope.changedVal = '';
};
$scope.changeLabelText = function () {
$scope.changedVal = $scope.textVal;
};
});
html
<!DOCTYPE html>
<html ng-app='myapp'>
<head>
<script data-require="jquery#*" data-semver="2.1.4" src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script data-require="angular.js#1.4.8" data-semver="1.4.8" src="https://code.angularjs.org/1.4.8/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" >
<script src="script.js"></script>
</head>
<body ng-controller="MainCtrl">
<input type="text" ng-model="textVal" ng-change="changeLabelText()">//change user name here//
<div ng-click="setText()">
<label>User Name</label><br/>
<input type="text" placeholder="enter username" value="{{changedVal}}">
</div>
</body>
</html>
If you want to update the label
var app = angular.module('myapp', []);
app.controller('MainCtrl', function($scope) {
$scope.textVal = 'User Name';
$scope.setText = function (element) {
$scope.textVal = 'User Name';
};
});
html
<body ng-controller="MainCtrl">
<input type="text" ng-model="textVal" ng-change="changeLabelText()">//change label here//
<div ng-click="setText()">
<i>Click here to reset</i><br/>
<label>{{textVal}}</label><br/>
<input type="text" placeholder="enter {{textVal}}" value="">
</div>
</body>

Issue with Angular don't see my data

I want that in the init to bind the model of my controller the init is called but I don't see any data what is wrong ?
Index.html
<!DOCTYPE html>
<html ng-app="I-Sign">
<head>
<meta http-equiv='X-UA-Compatible' content='IE=edge' />
<meta name="viewport" content="width=device-width" />
<title>Sign Language Application</title>
<link rel="stylesheet" href="scripts/jquery.mobile-1.4.5.css" />
<script type="text/javascript" charset="utf-8" src="scripts/jquery.js"></script>
<script type="text/javascript" charset="utf-8" src="scripts/jquery.mobile-1.4.5.js"></script>
<script type="text/javascript" charset="utf-8" src="scripts/angular.js"></script>
<script type="text/javascript" charset="utf-8" src="scripts/lodash.js"></script>
<script src="mainController.js"></script>
</head>
<body>
<div ng-controller="MainCtrl as ctrl" ng-init="init()">
<div id="categories">
     <ul data-role="listview" data-inset="true">
         <li ng-repeat="category in ctrl.data.categories"><a ng- click="ctrl.showWords(category)" href="#">
                 <img src="images/Can_I.png">
                 <h1>{{category.name}}</h1>
        </a>   
        </li>
</ul>
</div>
<div id="words">
    <ul data-role="listview" data-inset="true">
            
        <li ng-repeat="word in ctrl.currentWords"><a ng-click="ctrl.showMovie()" href="#">
                 <img src="images/Can_I.png">
                 <h1>{{word.name}}</h1>
        </a>                 
        </li>
</ul>
<div>
<input id="upBtn" class="ui-block-a" type="button" value="UP" ng-hide ng-click="ctrl.showCategories()">
</div>
</div>
mainController.js
var myApp = angular.module('I-Sign',[]);
myApp.controller('MainCtrl', ['$scope', function($scope) {
var self = $scope;
$scope.init = function () {
var that = this;
that.getData();
self.currentWords = [];
}
$scope.$watchCollection(function () {
//var that = this;
return self.data;
}, function () {
console.log("Changed");
});
$scope.getData = function () {
var that = this;
$.getJSON('data/database.json', function (data) {
that.data = data;
});
}
$scope.showCategories = function () {
var that = this;
$("#words").addClass("ng-hide");
$("#categories").removeClass("ng-hide");
$("#upBtn").assClass("ng-hide");
}
$scope.showWords = function (category) {
var that = this;
that.currentWords = [];
$("#categories").addClass("ng-hide");
$("#words").removeClass("ng-hide");
$("#upBtn").removeClass("ng-hide");
that.data.words.forEach(function (word) {
if (word.categoryId === category.id) {
that.currentWords.push(word);
}
});
}
}]);
Since you used jquery to get your data, you need to run a .$apply() as the code happened outside of angulars knowledge
$.getJSON('data/database.json', function (data) {
that.data = data;
$scope.$apply();
});
Alternatively you should not be using jquery at all and instead inject $http in (like you did with $scope) and use that:
$http.get('data/database.json')
.success(function(data){
that.data = data;
});
Additionally change the following:
$scope.showCategories = function () {
$scope.showCategories = true;
}
$scope.showWords = function (category) {
that.currentWords = [];
$scope.showCategories = false;
that.data.words.forEach(function (word) {
if (word.categoryId === category.id) {
that.currentWords.push(word);
}
});
}
and your html to:
<div id="categories" ng-show="showCategories">
<ul data-role="listview" data-inset="true">
<li ng-repeat="category in ctrl.data.categories">
<a ng-click="ctrl.showWords(category)" href="#">
<img src="images/Can_I.png">
<h1>{{category.name}}</h1>
</a>
</li>
</ul>
</div>
<div id="words" ng-show="!showCategories">
<ul data-role="listview" data-inset="true">
<li ng-repeat="word in ctrl.currentWords">
<a ng-click="ctrl.showMovie()" href="#">
<img src="images/Can_I.png">
<h1>{{word.name}}</h1>
</a>
</li>
</ul>
</div>
<div>
<input id="upBtn" class="ui-block-a" type="button" value="UP" ng-show="!showCategories" ng-click="ctrl.showCategories()">
</div>

Simple Backbone app not working

I wrote simple Backbone.js app from manual, but this does't work. Why?
It is a HTML-code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="main.css">
<script src="source/jquery.js"></script>
<script src="source/underscore.js"></script>
<script src="source/backbone.js"></script>
<script src="main.js"></script>
</head>
<body>
<div id="menu">
<ul>
<li>Start</li>
<li>Success</li>
<li>Error</li>
</ul>
</div>
<div id="start" class="block">
<div class="userplace">
<label>Enter name<input type="text" id="username"></label>
</div>
<div class="buttonplace">
<input type="button" id="button" value="Check">
</div>
</div>
<div id="error" class="block">
<p>Error - not found!</p>
</div>
<div id="success" class="block">
<p>Win!</p>
</div>
</body>
</html>
And it is a JS-code:
var Controller = Backbone.Router.extend({
routes: {
'': 'start',
'!/': 'start',
'!/error': 'error',
'!/success': 'success'
},
start: function() {
$('.block').hide();
$('#start').show();
},
error: function() {
$('.block').hide();
$('#error').show();
},
success: function() {
$('.block').hide();
$('#success').show();
},
});
var controller = new Controller();
var Start = Backbone.View.extend({
el: '#start',
events: {
'click #button': 'check'
},
check: function() {
console.log('WiN!');
if($("#username").val() == 'test') {
controller.navigate('success', true);
}
else {
controller.navigate('error', true);
}
}
});
var starter = new Start();
Backbone.history.start();
When I select point in menu, all work normal, but when I entered name into field and press button nothing happens. Event not activated. Why?
I think you're calling navigate incorrectly.
Try this:
controller.navigate('!/success', {trigger:true});
Documentation:
http://backbonejs.org/#Router-navigate

what is right way to change text in angular js?

<input type="button" class="button" value="click"/><div class="text_block">start</div>
In jquery this code is right for me:
$(".button").click(function() {
if($(this).val() == "click"){
$(this).val('clicked');
$(".text_block").html("stop");
}
else if($(this).val() == "clicked"){
$(this).val('click');
$(".text_block").html("start");
}
});
And how can I do this right using angular js?
AngularJs code sample
Use angular watch DEMO
var app = angular.module('my-app', [], function () {
})
app.controller('AppController', function ($scope) {
$scope.toggle = true;
$scope.$watch('toggle', function(){
$scope.toggleText = $scope.toggle ? 'Click' : 'Cliked';
$scope.divText = $scope.toggle ? 'Start' : 'Stop';
})
})
HTML code sample
<button ng-click="toggle = !toggle">{{toggleText}}</button>
<div class="box on" >{{divText}}</div>
You actually don't need a bit of javascript. You can do it in plain angular HTML code:
<input type="button" class="button" ng-model="toggle" ng-click="toggle = !toggle" value="{{toggle ? 'clicked' : 'click'}}" />
<div class="text_block">{{toggle ? 'Stop' : 'Start'}}</div>
Just create two local variable inside the scope and change their value according to the current value of clicked button.
Like :-
<body ng-controller="hello">
<input type="button" class="button" ng-click="click()" value="{{myvalue}}"/><div class="text_block">{{value}}</div>
<script>
var app=angular.module('app',[ ]);
app.controller("hello",function($scope){
$scope.value="STOP";//default value
$scope.myvalue="click";
$scope.click=function(){
if($scope.myvalue=="click"){
$scope.myvalue="clicked";
$scope.value="START";
}else{
$scope.myvalue="click";
$scope.value="STOP";
}
}
});
</script>
</body>
Here is the plunker:-
http://plnkr.co/edit/QsW1zzQF4BdslMwMFPxU?p=preview
live demo: http://plnkr.co/edit/zflkeo
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.3.x" src="https://code.angularjs.org/1.3.10/angular.js" data-semver="1.3.10"></script>
</head>
<body ng-controller="MainCtrl">
<button type="button" ng-click="theAngularWay()">{{btnState}}</button>
<div class="text_block">{{textBlock}}</div>
</body>
<script>
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.btnState = 'clicked';
$scope.textBlock = 'start';
$scope.theAngularWay = function() {
if($scope.textBlock === 'start') {
$scope.btnState = 'clicked';
$scope.textBlock = 'stop';
} else {
$scope.btnState = 'click';
$scope.textBlock = 'start';
}
}
});
</script
</html>
see
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body>
<div ng-app="" ng-controller="MyController">
<input type="button" class="button" value="{{Start}}" ng-click="showMessage()" /> <div class="text_block">{{message}}</div>
</div>
<script>
function MyController($scope) {
$scope.Start = "click";
$scope.message = "";
$scope.showMessage = function () {
if ($scope.Start == "click") {
$scope.Start = "clicked";
$scope.message = "stop";
}
else {
$scope.Start = "click";
$scope.message = "start";
}
}
}
</script>
</body>
</html>

Categories

Resources