var jem = 55;
var app = angular.module("store",[]);
app.controller("storeController",function(){
this.product = jem;
});
jem = 0;
<!DOCTYPE html>
<html ng-app="store">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-controller="storeController as store">
<p>{{"HI"}}</p>
<p>{{store.product}} </p>
</body>
</html>
Why does this output is "0" instead of "55"? Since jem is a basic javascript variable when product is assigned with jem it gets its value copied and should not change when jem is changed?
Notice that your controller definition is inside a callback function (as it should be...)
app.controller("storeController", function(){
this.product = jem;
});
A side effect of this, relevant to your question, is that the assignment statement within the callback, this.product = jem, will get executed after the assignment statement, jem = 0, outside of the callback.
The takeaway is that callbacks do not take place sequentially with the rest of your code.
Related
PLeaseHelp. it wont show the Value, even for form authentication, to get username & password values,I was trying the same methods.
<!DOCTYPE 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.0">
<title>Document</title>
</head>
<body>
<h1 id="result">Selected movie is </h1>
<select id="movie" onchange="showmovie()">
<option value="Spiderman">Spiderman</option>
<option value="Spiderman2">Spiderman2</option>
<option value="Spiderman3">Spiderman3</option>
</select>
</body>
</html>
<script>
var movie = document.getElementById("movie").value
function showmovie(){
alert("Changed")
document.getElementById("result").innerHTML="Movie chosen is"+movie
}
</script>
Try with this function showmovie
<script>
function showmovie() {
//Selected option
var selectedMovie = document.getElementById("movie").value;
document.getElementById("result").innerHTML = "Movie chosen is " + selectedMovie;
}
</script>
The issue here is because of the line var movie = document.getElementById("movie").value being executed just one time at the beginning (you could verify that adding console.log(movie); just after the movie variable declaration)
(movie stores then the value 'Spierdaman') and it never executes again with the calls for showmovie() function, so you could just move the movie declaration line above inside the function so it executes each time the action occurs and then having the good values.
Other details : To have a compliant code i suggest moving the script bloc to part just before and dont forget to add semicolons ';' at the end of each line ! + Better approach would be to use an eventListener as suggested by #T.J. Crowder in comments section above
This question already has answers here:
What is the purpose of the var keyword and when should I use it (or omit it)?
(19 answers)
Closed 4 years ago.
If I try to declare s as a variable it errors out. It is acting like s isn't a variable and really doesn't like any changes to the syntax at all.
I've actually written a decision tree webpage that relies on this concept a lot and I'm not sure why it works.
<!DOCTYPE html>
<html>
<head>
<title>Class Tests</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" charset="UTF-8"/>
<script src=" jQuery3.2.1.js"></script>
<script src=" jQuery_UI.js"></script>
</head>
<script>
function selection(select){
s = select;
}
$(document).ready(function(){
$("button").click(function(){
alert("boop " + s);
});
});
</script>
<body>
<button onclick=selection('Genius')>Genius</button>
<button onclick=selection('System')>Systems</button>
<button onclick=selection('Personal')>Personal</button>
</body>
</html>
A variable is undeclared when it does not use the var keyword. It gets created on the global object (that is, the window), thus it operates in a different space as the declared variables.
Find out more on this link
Variables that are assigned without var keyword are called undeclared. These are created in the global scope. So your s variable is available in the click handler.
Now this only happens in non-strict mode, so if you put 'use strict' directive inside or above the selection function you'll get an error.
<!DOCTYPE html>
<html>
<head>
<title>Class Tests</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" charset="UTF-8"/>
<script src=" jQuery3.2.1.js"></script>
<script src=" jQuery_UI.js"></script>
</head>
<script>
'use strict'
function selection(select){
s = select;
}
$(document).ready(function(){
$("button").click(function(){
alert("boop " + s);
});
});
</script>
<body>
<button onclick=selection('Genius')>Genius</button>
<button onclick=selection('System')>Systems</button>
<button onclick=selection('Personal')>Personal</button>
</body>
</html>
Setting your s like this:
function selection(select){
s = select;
}
is similar (for variable scope) to:
var s;
function selection(select) {
s = select;
}
So s exists as a property of window, and available both inside of selection function and for alert("boop " + s);, because window is a global object. But if you declare and assign a value to variable with var inside a function:
function selection(select) {
var s = select;
}
s will have only a scope of function selection, and retrieving it here:
alert("boop " + s);
causes an error, because it doesn't exist here.
I have a function that returns some HTML fragment that I store in a variable called data, with its whole structure. What I want is to extract from it some of those parts.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script id="hello">
</script>
</head>
<body>
</body>
</html>
For example, I want to get the body and save it in a new variable:
var body = data.split("<body")[1].split(">").slice(1).join(">").split("</body>")[0];
Where data is the HTML text as a string that the original function is returning.
Is there any way I could save an specific script, from its ID (in this case with id = hello), and save it in another variable??
Thank you very much
var newVar = $("#hello").html();
Let's suppose you have an HTML string in a variable, for example
var foo = '<body><span>bar</span></body>';
Now, let's initialize a parser, to convert this into HTML:
var parser = new DOMParser();
var doc = parser.parseFromString(foo, "text/html");
Now, you can read anything from foo, as it is converted into HTML:
document.getElementsByTagName("body")[0].innerHTML = doc.querySelectorAll("body")[0].innerHTML;
$html = document.querySelector("body").innerHTML;
$hello = document.getElementById("hello").innerHTML;
console.log($html);
console.log($hello);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script id="hello">
// script data
</script>
</head>
<body>
</body>
</html>
Been trying to take specific data from an array of objects that for many reasons I cannot host on a server. The data is in stored as a variable in the document. This is what i've been trying so far to no success:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
var users = [{"username":"nphillips7m","first_name":"Nicole","last_name":"Phillips","email":"nphillips7m#ebay.co.uk","gender":"Female","sexuality":"Networked static concept","language":"Gagauz"},
{"username":"esimpson7n","first_name":"Elizabeth","last_name":"Simpson","gender":"Female","sexuality":"Future-proofed solution-oriented definition","language":"Malay"},
{"username":"llawrence7o","first_name":"Lillian","last_name":"Lawrence","email":"llawrence7o#technorati.com","gender":"Female","sexuality":"Re-contextualized demand-driven middleware","language":"Tetum"}]
var simpson = users.find("last_name" + "Simpson")
document.getElementById("return").innerHTML = function myfunction() {
simpson;
}
</script>
</head>
<body>
<div id="return"></div>
</body>
For now I've just been trying to extract some/any data from the 'users' array, but going forward i would like to have the user search for a word and the entire 'line'/'lines' of data related to the word/words in 'users' display as results. What methods should i use to achieve this?
You have some mistakes in your code. First of all, find function accept as argument a callback function.
var simpson = users.find(a=>a.last_name=="Simpson");
If you pass function to innerHTML, you must to invoke it, like this:
document.getElementById("return").innerHTML = (function myFunction(){
return JSON.stringify(simpson);
})();
and function must return a value in order to set the HTML content (inner HTML) of result element.
var users = [{"username":"nphillips7m","first_name":"Nicole","last_name":"Phillips","email":"nphillips7m#ebay.co.uk","gender":"Female","sexuality":"Networked static concept","language":"Gagauz"},
{"username":"esimpson7n","first_name":"Elizabeth","last_name":"Simpson","gender":"Female","sexuality":"Future-proofed solution-oriented definition","language":"Malay"},
{"username":"llawrence7o","first_name":"Lillian","last_name":"Lawrence","email":"llawrence7o#technorati.com","gender":"Female","sexuality":"Re-contextualized demand-driven middleware","language":"Tetum"}]
var simpson = users.find(callback);
function callback(item){
return item.last_name=="Simpson";
}
document.getElementById("return").innerHTML = (function myFunction(){
return JSON.stringify(simpson);
})();
<body>
<div id="return"></div>
</body>
1. You need to pass the callback function in find method. The find method searches for an element in an array and returns the element if it is found. Otherwise undefined is returned. The Search Criteria is defined by a callback function. Something like
var simpson = users.find(currentValue => currentValue.last_name === "Simpson");
2. You might not require your innerHTML to be a function, instead it would be more appropriate that it points to meaningfull information like UserName Found.
document.getElementById("return").innerHTML = simpson.username;
Try the following code.
var users = [{"username":"nphillips7m","first_name":"Nicole","last_name":"Phillips","email":"nphillips7m#ebay.co.uk","gender":"Female","sexuality":"Networked static concept","language":"Gagauz"},
{"username":"esimpson7n","first_name":"Elizabeth","last_name":"Simpson","gender":"Female","sexuality":"Future-proofed solution-oriented definition","language":"Malay"},
{"username":"llawrence7o","first_name":"Lillian","last_name":"Lawrence","email":"llawrence7o#technorati.com","gender":"Female","sexuality":"Re-contextualized demand-driven middleware","language":"Tetum"}]
var simpson = users.find(currentValue => currentValue.last_name === "Simpson");
document.getElementById("return").innerHTML = simpson.username;
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
</script>
</head>
<body>
<div id="return"></div>
</body>
I have a string like var message = "you are moving to {{output.number}}";
I want this to be put to div element. i tried using $("#message").html(message);
but it just printed the whole string for me. I want to have the output.number print the value it had. Is it possible to achieve what i want?
I am using angular.js 1.5.
Use $interpolate service like:
var message = $interpolate("you are moving to {{number}}")(output)
// or
var message = $interpolate("you are moving to {{output.number}}")($scope)
I hope you are looking for something like this. You can do it by using the scope variable inside the controller.
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.bootcss.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="number" ng-model="output.number" />
<button ng-click="AppendItem()">Append</button>
<div id="message"></div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.output = {};
$scope.AppendItem = function () {
var string = "Your Number is " + $scope.output.number;
$("#message").html(string);
}
});
</script>
</body>
</html>
You are almost there just try :
$scope.output.number = '123';
var message = "you are moving to" + output.number;
$("#message").html(message);
Don't put variable inside "" quotes.
When we are going to append a string variable to another string variable then we need to use append operator ie., "+". Here is an example.
var output.number = 10;
var message = "you are moving to " + output.number;
$("#message").html(message);
You can do like this using $compile:
$compile(angular.element(document.querySelectorAll('#message')[0]).html("you are moving to {{output.number}}"))($scope);
Add $compile as dependency in your controller.
All the best.
You can try this:
<html ng-app="app">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body ng-controller="appCtrl">
<p id="message"></p>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"> </script>
</body>
JS:
Should not write DOM Manipulation code inside controller, but can get the idea how to do it.
var app = angular.module('app', []);
app.controller('appCtrl', function($scope, $interpolate){
var msg = "you are moving to {{number}}";
$scope.number = 10;
$('#message').html($interpolate(msg)($scope));
});