Some problems with Angular JS and Javascript - javascript

I'm a newbie in Javascript and Angular JS programming and I'm trying to make a currency converter using Yahoo Finance API, but also I want to input directly the initial value in the script without clicking the button or pressing enter, so i figured that using Angular JS would be great. But it doesn't work properly and I think the problem might be in function calculate($scope). Please, can you help me?
<html ng-app>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function httpGet(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
function currencyConverter(currency_from,currency_to,currency_input){
var yql_base_url = "https://query.yahooapis.com/v1/public/yql";
var yql_query = 'select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20("'+currency_from+currency_to+'")';
var yql_query_url = yql_base_url + "?q=" + yql_query + "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
var http_response = httpGet(yql_query_url);
var http_response_json = JSON.parse(http_response);
return http_response_json.query.results.rate.Rate;
}
//The problem starts here?
function calculate($scope)
{
$scope.total= function(){
var currency_from = "USD";
var currency_to = "INR";
var rate = currencyConverter(currency_from,currency_to,$scope.currency_input);
return rate;
};
}
</script>
<script src="js/angular.js"></script>
</head>
<body>
<div ng-controller="calculate">
<div style="float:left;">
<form>
<input type="text" ng-model="currency_input" value="0"/> =
</form>
</div>
<div style="float:left">
{{total()}}
</div>
</div>
<div style="clear: both;"></div>
</body>
</html>

There are a few erros in your code using AngularJS. You forgot to start your application module and add a controller.
I made a few corrections and I tested, it is working:
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
</head>
<body>
<div ng-controller="MyController">
<div style="float:left;">
<form>
<input type="text" ng-model="currency_input" ng-change="total()" value="0"/> =
</form>
</div>
<div style="float:left">
{{ rate }}
</div>
</div>
<div style="clear: both;"></div>
<script>
angular.module('app', [])
.controller('MyController', function($scope, $http) {
function currencyConverter(currency_from,currency_to) {
var yql_base_url = "https://query.yahooapis.com/v1/public/yql";
var yql_query = 'select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20("'+currency_from+currency_to+'")';
var yql_query_url = yql_base_url + "?q=" + yql_query + "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
$http.get(yql_query_url).then(function(response) {
$scope.rate = $scope.currency_input*response.data.query.results.rate.Rate;
});
}
$scope.total = function() {
var currency_from = "USD";
var currency_to = "INR";
currencyConverter(currency_from, currency_to);
};
});
</script>
</body>
</html>
I don't recommend you to use jquery to make http calls. Use $http instead!

One problem, which should be the first to be corrected and go from there, is that you are referencing an angular concept $scope in your scripts before you actually declare the angular library.
To correct this, move your angular library script tag up above your other script tag (but below the jquery script tag.

You should take a look at services (https://docs.angularjs.org/guide/services).
With that you can just create a service and put all of your 'Yahoo' related functions in one place. Then just inject it into your directive/controller.
ex:
.service('yahooRelatedLogicSrvc', function () {
return {
httpGet: function httpGet(theUrl) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
}
})
.controller('sampleCtrl', function ($scope, yahooRelatedLogicSrvc) {
var url = 'http://yahoo.com';
$scope.httpGet = yahooRelatedLogicStvc.httpGet(url);
}
And you can just put returns of your service functions as $scope properties etc.
I really can see why you should use in line javascript in that scenario.

Angular makes something like this much easier than what you're attempting. There's an $http service for performing a GET, for one, so you can leave out jquery and create something much simpler like ConverterService in my example.
Since your input is bound to a scope variable, you don't need to set value="0", simply set $scope.currency_input to your default value in your controller. I created a convert function on the scope, which will update the output whenever its called. It's called once at the bottom of the controller, but could be bound to a button in your html by simply doing something like this: <button ng-click="convert()">Convert value</button>
var app = angular.module('calc', []);
app.controller('MainCtrl', function($scope, ConverterService) {
// default your currency input
$scope.currency_input = 10;
var currency_from = "USD";
var currency_to = "INR";
$scope.convert = function() {
ConverterService.getConversions(currency_from, currency_to)
.then(function(response) {
// put your logic to convert the value here
var convertedVal = null; // = $scope.currency_input * response.something etc...
$scope.result = convertedVal;
});
};
$scope.convert();// run once when the controller loads to get defaulted input conversion
});
app.factory('ConverterService', function($http) {
return {
getConversions: function(from, to, val) {
var endpoint = ''; // build your endpoint here
return $http.get(endpoint);
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="calc">
<div ng-controller="MainCtrl">
<input type="text" ng-model="currency_input">= {{result}}
</div>
</html>

Related

How to get the Local Storage data into the view file Using Angular js

Hello I am beginner in mean Stack. and I have data in localstorage and I want to fetch the data from the local storage and show in html file but I don't know How to get it. on the view file.
$scope.useredit = function (d) {
var user_id = d._id;
var dataToModify;
angular.forEach($scope.dp, function (value, key) {
if (user_id == value._id) {
dataToModify = value;
$localStorage.userData = dataToModify;
console.log($localStorage.userData.name);
$location.path('/useredit');
}
});
}
when I type localStorage; into console it show
ngStorage-userData
:
"{
"_id":"5846692617e0575c0e0c2211",
"password":123456,
"email":"montyy1981#gmail.com",
"name":"digvijay12","__v":0
}"
How to get it value into the view file.I used like
<div>{{userData.email}}</div>
But it is not showing data.please help me how to fetch localstorage data and show into view file.
You can use core concept without ngStorage....
https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage
localStorage.setItem("userData", $scope.Data);
$scope.storageData = localStorage.getItem("userData");
<p>{{storageData.email}}</p>
How to get the localStoragedata anywhere this is very simple we have to pass localStorage data into the controller global variable suppose
we have the data into localstorage
$scope.useredit = function (d) {
var user_id = d._id;
var dataToModify;
angular.forEach($scope.dp, function (value, key) {
if (user_id == value._id) {
dataToModify = value;
$localStorage.userData = dataToModify;
console.log($localStorage.userData.name);
$location.path('/useredit');
}
});
}
we have to define pass $localStorage.userData into the other variable after controller start.
app.controller("usercontroller",function($scope,$http, $localStorage,$location){
$scope.registeruser = $localStorage.userData;
$scope.useredit = function (d) {
var user_id = d._id;
var dataToModify;
angular.forEach($scope.dp, function (value, key) {
if (user_id == value._id) {
dataToModify = value;
$localStorage.userData = dataToModify;
console.log($localStorage.userData.name);
$location.path('/useredit');
}
});
}
});
For better understanding click this DEMO
In the controller you need to inject "ngStorage" angular.module('MyApp', ["ngStorage"]).
And add the dependency script link <script src="https://cdn.jsdelivr.net/ngstorage/0.3.6/ngStorage.min.js"></script>
HTML
<html ng-app="MyApp">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
<script src="https://cdn.jsdelivr.net/ngstorage/0.3.6/ngStorage.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="MyController">
<input type="button" value = "Save" ng-click = "Save()" />
<input type="button" value = "Get" ng-click = "Get()" />
</div>
</body>
</html>
Script.js
var app = angular.module('MyApp', ["ngStorage"])
app.controller('MyController', function ($scope, $localStorage, $sessionStorage, $window) {
$scope.Save = function () {
$localStorage.email = "xyz#gmail.com";
}
$scope.Get = function () {
$window.alert($localStorage.email);
}
});
Hope it will be usefull for you.

SAPUI5 and dynamic URL for OData service

I am doing sample example using sapui5. I want to pass URL service dynamically and load ODATA service, but I really new with sapui5 and I don’t know how to do it.
This code below is what i tried to do but it is not working. Thanks a lot for your help.
createContent : function(oController) {
var oLayout = new sap.ui.commons.layout.AbsoluteLayout({width:"340px",height:"150px"});
oLayout.addStyleClass("CustomStyle"); //Add some additional styling for the border
var oLabel = new sap.ui.commons.Label({text:"Service Url"});
var oUrlInput = new sap.ui.commons.TextField({width:"190px"});
oLabel.setLabelFor(oUrlInput);
oLayout.addContent(oLabel, {right:"248px",top:"20px"});
oLayout.addContent(oUrlInput, {left:"110px",top:"20px"});
var oLabel = new sap.ui.commons.Label({text:"Service"});
var oSvcInput = new sap.ui.commons.TextField({width:"190px"});
oLabel.setLabelFor(oSvcInput);
oLayout.addContent(oLabel, {right:"248px",top:"62px"});
oLayout.addContent(oSvcInput, {left:"110px",top:"62px"});
var loadData =new sap.ui.commons.Button({
text : "load",
width:"133px",
press: function() {
oController.load();
}});
oLayout.addContent(loadData, {left:"110px",top:"104px"});
return oLayout;
}
// Controller
load: function(oEvent){
var url = sap.ui.getControl("oUrlInput").getValue();
var svc = sap.ui.getControl("oSvcInput").getValue();
var oModel = new sap.ui.model.odata.OdataModel(url + "/" + svc ,false);
var mylist = new sap.ui.model.ListBinding(oModel);
return mylist;
}
// index.html
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/>
<script src="resources/sap-ui-core.js"
id="sap-ui-bootstrap"
data-sap-ui-libs="sap.ui.commons,sap.ui.table,sap.ui.ux3"
data-sap-ui-theme="sap_bluecrystal">
</script>
<!-- add sap.ui.table,sap.ui.ux3 and/or other libraries to 'data-sap-ui-libs' if required -->
<script>
sap.ui.localResources("simpleform");
var view = sap.ui.view({id:"idsimpleForm1", viewName:"simpleform.simpleForm", type:sap.ui.core.mvc.ViewType.JS});
view.placeAt("content");
</script>
</head>
<body class="sapUiBody" role="application">
<div id="content"></div>
</body>
</html>
You have to give your controls an id to access them in the controller. Like this:
// create controls with id
var oLabel = new sap.ui.commons.Label("oLabelId", {text:"Service Url"});
var oUrlInput = new sap.ui.commons.TextField("oUrlInputId", {width:"190px"});
// then to get reference to the control later
var oLabel = sap.ui.getCore().byId("oLabelId");
var oUrlInput = sap.ui.getCore().byId("oUrlInputId");
Make sure, that you use the right Url:
var oModel = new sap.ui.model.odata.OdataModel("/sap/opu/odata/sap/" + svc ,false);
Make sure following.
Change the case of odataModel to ODataModel
Ensure the Service URL also correct
Obtain the reference of the control As described by kjokinen
Regards

Issue trying to get website to work - possible issue with my html code?

SO I have code that I'm trying to implement from my jsfiddle into an actual working website/mini-app. I've registered the domain name and procured the hosting via siteground, and I've even uploaded the files via ftp so I'm almost there...
But I'm thinking there's something wrong with my HTML code or JS code or how I implemented my JS code into my HTML code, because all of the HTML and CSS elements are present, but the javascript functionality is absent.
Here is my fiddle:
jsfiddle
^^ Click on start to see the display in action (which doesn't work in the actual website, which leads me to believe there's an issue with my JS file - whether it be code-related or whether that's because I integrated the file incorrectly) (or maybe even uploaded to the server incorrectly, perhaps?)...
And here is the actual site:
http://www.abveaspirations.com/index.html
And here's my HTML code uploaded to the server via FTP:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id='frame'>
<div id='display'>
<h1 id='output'></h1>
</div>
</div>
<div class="spacer">
</div>
<div id="main"> <!-- 11main -->
<h1 id='consoleTitle'>Control Board</h1>
<h5 id='consoleSub'><i>Double-click on an entry to remove. And add entries to your heart's desire...</i></h5>
<div id="controlbox"> <!-- ##controlbox -->
<div id="controlpanel"></div>
<div class="spacer"></div>
<div id="formula"> <!--formula -->
<form id="frm" method="post">
<input id="txt" type="text" placeholder="Insert your own entry here..." name="text">
<input id='submitBtn' type="submit" value="Start">
<input id='stop' type="button" value="Stop">
<select id="load1">
<option id='pre0' value="Preset 0">Preset 0</option>
<option id='pre1' value="Preset 1">Preset 1</option>
<option id='pre2' value="Preset 2">Preset 2</option>
</select>
<!-- These are for buttons as opposed to OPTION...
<input id="load" type="button" value="Preset 1">
<input id="load2" type="button" value="Preset 2"-->
</form>
</div> <!-- formula -->
</div> <!-- ##controlbox -->
</div> <!-- 11main -->
</body>
And my JS code, also uploaded to server via FTP (I didn't include the accompanying CSS file, but if that would help, I can provide ):
$(document).ready(function () {
var txtBox = $('#txt');
var frm = $('#frm');
var output = $('#output');
var subBtn = $('#submitBtn');
var stopBtn = $('#stop');
var loadBtn = $('#load');
var loadBtn2 = $('#load2');
var loadBtnA = $('#load1');
var pre0 = $('#pre0');
var pre1 = $('#pre1');
var pre2 = $('#pre2');
var txt = $('#display');
var preset1 = ["1", "2", "3"];
var preset2 = ["a", "b", "c"];
var container = ["What we do in life echoes in all eternity.", "Find your purpose and give it life.", "When you work your hardest, the world opens up to you."];
var console = $('#controlpanel');
var oldHandle;
function loadPreset0() {
container = [];
console.empty();
container = ["What we do in life echoes in all eternity.", "Find your purpose and give it life.", "When you work your hardest, the world opens up to you."];
updateConsole();
};
function loadPreset1() {
container = [];
console.empty();
container = preset1;
updateConsole();
};
function loadPreset2() {
container = [];
console.empty();
container = preset2;
updateConsole();
};
$(pre0).data('onselect', function() {
loadPreset0();
});
$(pre1).data('onselect', function() {
loadPreset1();
});
$(pre2).data('onselect', function() {
loadPreset2();
});
$(document).on('change', 'select', function(e) {
var selected = $(this).find('option:selected'),
handler = selected.data('onselect');
if ( typeof handler == 'function' ) {
handler.call(selected, e);
}
});
function updateConsole() {
for (var z = 0; z < container.length; z++) {
var resultC = container[z];
var $initialEntry = $('<p>' + '- ' + resultC + '</p>');
console.append($initialEntry);
};
};
updateConsole();
frm.submit(function (event) {
event.preventDefault();
if (txtBox.val() != '') {
var result = txtBox.val();
container.push(result); //1.
var resultB = container[container.length-1];
var $entry = $('<p>' + '- ' + resultB + '</p>');
console.append($entry); //2.
}
var options = {
duration: 5000,
rearrangeDuration: 1000,
effect: 'random',
centered: true
};
stopTextualizer();
txt.textualizer(container, options);
txt.textualizer('start');
txtBox.val('');
});
$("#controlbox").on('dblclick', 'p', function() {
var $entry = $(this);
container.splice($entry.index(), 1);
$entry.remove();
});
function stopTextualizer(){
txt.textualizer('stop');
txt.textualizer('destroy');
}
$(stopBtn).click(function() {
stopTextualizer();
});
});
Any help would be appreciated. I guess I'm just not sure what to do after uploading the html file to the server via ftp. Or maybe I did that correctly and there's something wrong with my code that I'm overlooking. Basically I'm lost. So help please!
You forgot to load jQuery. Make sure that you use <script src="../path-to-jquery/jquery.js"></script> before you load your script.js script.
Also, I noticed that you're loading your scripts in the head tag. This is bad practice, load them right before </body>.
I believe your site is missing jQuery. Add this to the top of your code to hotlink to google's jQuery.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

Setting a knockout observable using sammy for routing

I have a SPA using knockout JS for data binding and sammy for routing. I have a deck of cards that I am trying to have a dynamic routing to. My problem is that it doesn't work when I try to set a knockout observable from the routing function in sammy.
My HTML, where I try to bind the name of the deck, looks like this:
<!-- Create Deck -->
<div id="createDeck" class="page" style="display:none;">
<input type="text" class="form-control" placeholder="Untitled Deck..." data-bind="value: $root.deck.name" />
</div>
<script type="text/javascript" src="lib/jquery-1.9.1.js"></script>
<script type="text/javascript" src="lib/knockout-2.3.0.js"></script>
<script type="text/javascript" src="lib/bootstrap.min.js"></script>
<script type="text/javascript" src="lib/sammy.js"></script>
<script type="text/javascript" src="js/Models/Deck.js"></script>
<script type="text/javascript" src="js/Models/Card.js"></script>
<script type="text/javascript" src="js/ViewModels/DeckViewModel.js"></script>
<script type="text/javascript" src="js/ViewModels/CardViewModel.js"></script>
<script type="text/javascript" src="js/routing.js"></script>
The Deck.js and DeckViewModel.js looks like below
function Deck(deckid, name, cards) {
var self = this;
self.id = deckid;
self.name = name;
self.cards = cards;
}
function DeckViewModel(deck, cards) {
var self = this;
self.deck = ko.observable(deck);
self.cards = ko.observableArray(cards);
self.goToCard = function (card) { location.hash = card.deckid + '/' + card.id };
}
// Bind
var element = $('#createDeck')[0];
var deckView = new DeckViewModel(null, null);
ko.applyBindings(deckView, element);
Finally, in my routing I try to create a new Deck, like this:
// Client-side routes
(function ($) {
var app = $.sammy('#content', function () {
this.get('#deck/:id', function (context) {
showPage("createDeck", ": Create Deck");
console.log(this.params.id);
deckView.deck = new Deck(1, "test", null);
console.log(deckView.deck);
});
});
$(function () {
app.run('#/');
});
})(jQuery);
function showPage(pageID, subHeader) {
// Hide all pages
$(".page").hide();
// Show the given page
$("#" + pageID).show();
// change the sub header
$("#subHeader").text(subHeader);
}
As you can see, I'm trying to create a test deck with the name 'test', but the binding <input type="text" class="form-control" placeholder="Untitled Deck..." data-bind="value: $root.deck.name" /> seems to bind the letter 'c'.
I'm at a loss, please help.
I tried to make a jsfiddle to demonstrate my problem
In your code the value assignment is not correct unless you are using Knockout-es5 plugin. here is the correct code
var app = $.sammy('#content', function () {
this.get('#deck/:id', function (context) {
showPage("createDeck", ": Create Deck");
console.log(this.params.id);
deckView.deck(new Deck(1, "test", null));
console.log(deckView.deck());
});
});
The way I've done this before is to define my Sammy() routes within the ViewModel. Shorter example for brevity:
(function($) {
function ViewModel() {
var self = this;
self.deckId = ko.observable(null);
Sammy(function() {
this.get('#/deck/:deckId', function(context) {
self.deckId(this.params.deckId);
});
});
}
$(function() {
ko.applyBindings(new ViewModel());
});
})(jQuery);
That way you can access your observables, etc, via self.

calling more than one function on the same button does not work for me (ajax)

i got a ajax procedure that is working ok, but now i need to add a new function to be called just once. so i add this to my current script to get the apex collection clean, but now nothing happens, i placed an alert to verify, but no alert is shown, i guess is because i am placing my clean script in wrong place or there must be something else missing.
// Clean Collection
function()
{
alert('Clean All');
var ajaxRequestd = new htmldb_Get(null,&APP_ID.,"APPLICATION_PROCESS=DEL_PRODUCTS",&APP_PAGE_ID.);
ajaxResult = ajaxRequestd.get();
}
here is my full script. thanks for your value tips !!
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Totals</title>
<script type="text/javascript">
$(function()
{
$("#Calculate").click
(
function()
{
// Clean Collection
function()
{
alert('Clean All');
var ajaxRequestd = new htmldb_Get(null,&APP_ID.,"APPLICATION_PROCESS=DEL_PRODUCTS",&APP_PAGE_ID.);
ajaxResult = ajaxRequestd.get();
}
$("input[name=f_qty]").each
(
function()
{
var valueInCurrentTextBox = $(this).val();
var productId = $(this).parents('tr').find("input[name=f_prod_id]").val();
$("#P12_PRODUCT_ID").val(productId);
if (valueInCurrentTextBox != '')
{
$("#P12_QTY").val(valueInCurrentTextBox);
var ajaxRequest = new htmldb_Get(null,&APP_ID.,"APPLICATION_PROCESS=ADD_PRODUCTS",&APP_PAGE_ID.);
ajaxRequest.add('P12_PRODUCT_ID',html_GetElement('P12_PRODUCT_ID').value);
ajaxRequest.add('P12_QTY',html_GetElement('P12_QTY').value);
ajaxResult = ajaxRequest.get();
}
}
);
alert('Updated!');
}
);
}
);
</script>
</head>
<body>
<div id="totals"></div>
<p align="center" style="clear: both;">
<button type="button" style="font-weight: bold;background-color:lightgray;margin-left:auto;margin-right:auto;display:block;margin-top:0%;margin-bottom:0%" id="Calculate">Add Products</button>
</p>
</body>
</html>
You're declaring that inner function, but never actually calling it. You could assign it to a variable and then call that, but it's actually not needed at all.
Try:
$(function()
{
$("#Calculate").click
(
function()
{
// Clean Collection
alert('Clean All');
var ajaxRequestd = new htmldb_Get(null,&APP_ID.,"APPLICATION_PROCESS=DEL_PRODUCTS",&APP_PAGE_ID.);
ajaxResult = ajaxRequestd.get();
$("input[name=f_qty]").each
(
function()
{
var valueInCurrentTextBox = $(this).val();
var productId = $(this).parents('tr').find("input[name=f_prod_id]").val();
$("#P12_PRODUCT_ID").val(productId);
if (valueInCurrentTextBox != '')
{
$("#P12_QTY").val(valueInCurrentTextBox);
var ajaxRequest = new htmldb_Get(null,&APP_ID.,"APPLICATION_PROCESS=ADD_PRODUCTS",&APP_PAGE_ID.);
ajaxRequest.add('P12_PRODUCT_ID',html_GetElement('P12_PRODUCT_ID').value);
ajaxRequest.add('P12_QTY',html_GetElement('P12_QTY').value);
ajaxResult = ajaxRequest.get();
}
}
);
alert('Updated!');
});
});

Categories

Resources