Calling a JavaScript function linked to my project using ng-click - javascript

I need to call a JavaScript function which is linked to my project. This function has 3 parameters. I'm using this parameters from an array on a ng-repeat.
If I use onclick event with 3 predefined parameter the function is executed with no problem. However, if I try to pass the parameters on the onclick function using {{a.param}}, it doesn't work.
If I try to use ng-click using the function and passing the parameters using {{a.param}} or a.param also does not work.
Can I call my JavaScript function from scope? I cannot define the JavaScript function on scope as I have seen in many articles.

Check out this:
(function(){
var app = angular.module("app",[]);
var module = angular.module("app");
module.controller("controller", function(){
var model=this;
model.param1="not initialized";
model.param2="not initialized";
model.param3="not initialized";
model.doWork = function(param1,param2,param3)
{
model.param1=param1;
model.param2=param2;
model.param3=param3;
};
});
}());
<!DOCTYPE html>
<html>
<head>
<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" />
<script src="script.js"></script>
</head>
<body ng-app="app">
<div ng-controller="controller as model">
{{model.param1}}
<br/>
{{model.param2}}
<br/>
{{model.param3}}
<input type="button" value="Click" ng-click='model.doWork("this is param1",model.param2,"Some random string")')>
</div>
</body>
</html>
Hope it helps!

Related

Angularjs: Object property value does not update

I know there are multiple questions related to my issue, but I still have problem fixing this. I have the following html and JavaScript code:
<!doctype html>
<html ng-app="Demo">
<head>
<meta charset="utf-8" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
</head>
<body ng-controller="AppController">
<input type="" name="" ng-model="docs[1].value">
{{m3.value}}
{{m4}}
<script type="text/javascript">
var app = angular.module('Demo', []);
app.controller(
"AppController",
function( $scope ) {
$scope.docs=[{value:"first doc"}, {value:"second doc"}];
$scope.m3=$scope.docs[1];
$scope.m4=$scope.docs[1].value;
}
);
</script>
</body>
</html>
When I type in the input, the m3.value gets updated but m4 does not! I can't figure out why this is happening. Any comment is appreciated.
Statement 1 :
$scope.m3=$scope.docs[1];
This statement storing the reference for model docs[1]
so, {{m3.value}} will get updated model value.
Statement 2 :
$scope.m4=$scope.docs[1].value;
This statement copying the actual primitive value.
so, {{m4}} still get old value
Ok so the way I solved it is to add a watcher to m3.value:
$scope.$watch('m3.value', function(){
console.log('Changing');
$scope.m4 = $scope.m3.value;
});
And now $scope.m4 updates.

How to compare only output part in html and javascript?

I have a plan to create an app for JavaScript test. In here I will give a question for creating a program, for example, show the text "HTML Code Play" in alert box? The user will do the coding, and they can use any name for the functions, variable, etc.
I want to check the output, where the output show the alert box "HTML Code Play".
User Code
<script>
function showalert()
{
alert("HTML Code Play");
}
</script>
<input type="button" value="Show Alert" onclick="showalert();">
Compare with the following code(My code)
<button onclick="alertbox();">Show Alert</button>
<script>
function alertbox()
{
alert("HTML Code Play");
}
</script>
In the examples above, both produce the same output but the coding is different.
When I check both codes, I want the result true. Can I do it? Is it possible?
I found your question interesting, and created sample code using mocha and sinon.
(To exec this, you must install sinon.js modules by yourself.)
I published this code here as working code.
Please regard 'code1','code2' blocks as user-implemented codes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>How to test user code on broweer</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.5.3/mocha.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.5.3/mocha.css" rel="stylesheet">
<script type="text/javascript" src="../components/sinon/lib/sinon.js"></script>
<script type="text/javascript" src="../components/sinon/lib/sinon/util/core.js"></script>
<script type="text/javascript" src="../components/sinon/lib/sinon/extend.js"></script>
<script type="text/javascript" src="../components/sinon/lib/sinon/spy.js"></script>
<script type="text/javascript" src="../components/sinon/lib/sinon/call.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>How to test user code on broweer</h1>
<div id="mocha"></div>
<div id="live-code-stage"></div>
<template id="code1">
<button onclick="alertbox();">Show Alert</button>
<script>
function alertbox() {
alert("HTML Code Play");
}
</script>
</template>
<template id="code2">
<script>
function showalert() {
alert("HTML Code Play");
}
</script>
<input type="button" value="Show Alert" onclick="showalert();">
</template>
</div>
<script>
mocha.setup('bdd');
$(function () {
var assert = function (expr, msg) {
if (!expr) throw new Error(msg || 'failed');
};
describe("implement 'show alert button' test", function () {
before(function () {
window.alert = sinon.spy();
});
it("window.alert must to be called with 'HTML Code Play'", function (done) {
$("#live-code-stage").html($("#code1").html()); // testing code1
$("button, input[type='button']").click();
assert(window.alert.calledWith("HTML Code Play"));
done();
});
});
mocha.run();
});
</script>
</body>
</html>
Key Points
You can mock 'window.alert' like this:
window.alert = sinon.spy();
And you can check if it(=alert) was called with correct argument like this:
assert(window.alert.calledWith("HTML Code Play"));
If user-created code is wrong, mocha test will fail.
Introducing qunit may improve the test report appearance.
But this is just a sample. There must be many options to archive what you want.

Why is my jQuery script written in notepad++ not working on files stored locally?

I tried to do a simple slider but that did not work, so i am copying one of code cademy, but it still qont work.
I have used 4 different browsers all have the same problem, i can type in the box but wont post, and show below.
PLEASE HELP?
Html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<link href="http://s3.amazonaws.com/codecademy-content/courses/ltp2/css/bootstrap.min.css" rel="stylesheet">
<link href='http://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
<link type='text/css' href="stylesheet.css" rel="stylesheet">
</head>
<body>
<div class="container">
<form>
<div class="form-group">
<textarea class="form-control status-box" rows="2" placeholder="What's on your mind?"></textarea>
</div>
</form>
<div class="button-group pull-right">
<p class="counter">140</p>
Post
</div>
<ul class="posts">
</ul>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
AMMENDED
script.js
$(document).ready() {
$('.btn').click(function() {
var post = $('.status-box').val()
$('<li>').text(post).prependTo('posts');
});
};
THANK YOU ALL, this has been corrected and it now works :)
val is a jQuery function ... you need () to invoke it so it returns the value of element. As your code stands now you are trying to set a function object as text.
You are also using incorrect selectors $('btn') and $('status-box') which are looking for non existent tags <btn> and <status-box>.
Add dot prefix for both to represent class:
$('.btn') and $('.status-box')
As well as what's been mentioned in the other answer, I don't believe your main method is ever called. If it isn't called then the event handler isn't going to be attached.
The main method would be easier set up via jquery, so instead of:
var main = function() {
$('btn').click(function() {
var post = $('status-box').val
$('<li>').text(post).prependTo('.posts');
});
}
Just do:
$(function() {
$('btn').click(function() {
var post = $('status-box').val
$('<li>').text(post).prependTo('.posts');
});
});
Alternatively you could adjust your body tag as follows:
<body onload="main()">

Can't add jQuery handler to HTML site

I have a single page site:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.5/leaflet.css" />
<link type="text/css" rel="stylesheet" href="stylesheet.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.7.5/leaflet.js"></script>
</head>
<body>
<h1>Hello World</h1>
<p>I'm hosted with GitHub Pages.</p>
<div id="map"></div>
<FORM>
<INPUT id="but" Type="BUTTON" Value="About Me" />
</FORM>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src=script.js></script>
</body>
</html>
And I would like to add some handler to button #but, and try to use with script in script.js:
var mapClicked = function() {
alert("Map!");
// create a map in the "map" div, set the view to a given place and zoom
//var map = L.map('map').setView([55.432, 37.654], 13);
}
$(document).ready(function() {
$('#but').click(mapClicked());
});
But then I run this html in browser and click to button, nothing happens.
By adding () to the function name when referencing the function by it's name. This will call the function directly and the returned value will be assigned as callback of the click event. By removing () of the function name(or rather function call), the function is referenced correctly and called when the click event occurs on the element.
Change
$('#but').click(mapClicked());
to
$('#but').click(mapClicked); // <----- Removed ()

How to use a javascript instance in jquery/Select a javascript handle via jquery?

As a jquery-beginner, i should bind a javascript object into my jquery functions, like:
<div title="StackOverflow" onclick="javascript:action(this)">Content</div>
and in action i will handle the "this" :
function action(instance){
example=instance.attr("title");
}
but the "instance" is not a jquery object so i can't work with it. The syntax
example=$(instance).attr("title");
doesn't help me either.
I'd be glad of any suggestions
If you're using jQuery then you should completely separate the definition of your HTML and associated JavaScript. For example
HTML:
<div id="soDiv" title="StackOverflow">Content</div>
JavaScript:
$(document).ready(function() {
$('#soDiv').click(function() {
var example = $(this).attr('title');
...
});
});
this should work...
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
function action(instance){
example=$(instance).attr("title");
alert(example);
}
</script>
</head>
<body>
<a id="test" title="StackOverflow" onclick="javascript:action(this)" href="#">Content</a>
</body>
</html>
// HTML file
<div title="StackOverflow" id="stackoverflow">Content</div>
// JS File
document.getElementById("stackoverflow").addEventListener("click", function () {
var example = this.getAttribute("title");
});
Seperations of concerns
HTML:
<div title="StackOverflow" id="stack">Content</div>
Javascript (with jQuery):
$('#stack').click(function(){
alert(this.title);
});

Categories