get value of angular js expression in window.alert in angularJs - javascript

Hi I am trying to alert the value of an expression in angularJs
I am quite new to angular and am just trying to work out how grab the value of the expression in an alert or in the console.
I am using AngularJs with json, below is my code
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.3/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app='app'>
<div ng-controller="ListCtrl">
<ul>
<li ng-repeat="menu in menus" id="{{menu.id}}" class="{{menu.cssClass}}">
<a ng-href="{{menu.content}}" ng-click="doGreeting(greeting)">{{menu.description}}</a>
<ul>
<li ng-repeat="submenu in menu.menu" id="{{submenu.id}}" class="{{submenu.cssClass}}">
<a ng-href="{{submenu.content}}" ng-click="ShowAlert()">{{submenu.description}}</a>
</li>
</ul>
</li>
</ul>
</div>
</body>
</html>
JAVASCRIPT
var app = angular.module("app", []);
app.controller("ListCtrl", ["$scope", "$http", "$window",
function($scope, $http, $window) {
$http.get('menu.json')
.then(function(response) {
$scope.menus = response.data.menus; // response data
$scope.greeting = 'Hello, World!';
$scope.ShowAlert = function () {
$window.alert("{{menu.content}}");
}
});
}
]);
JSON
{
"menus":[
{
"id":"contact",
"leaf":true,
"description":"Contact Us",
"link":"",
"content":"contactUs.html",
"cssClass":"static-content",
"menu":null
},
{
"id":"rules",
"leaf":false,
"description":"Sports Betting Rules",
"link":"",
"content":"",
"cssClass":"",
"menu":[
{
"id":"types",
"leaf":true,
"description":"Wager Types",
"link":"",
"content":"wagerTypes.html",
"cssClass":"static-content wager-types",
"menu":null
},
{
"id":"odds",
"leaf":true,
"description":"Odds & Lines",
"link":"",
"content":"oddsAndLines.html",
"cssClass":"static-content",
"menu":null
},
{
"id":"policies",
"leaf":true,
"description":"Rules & Policies",
"link":"",
"content":"rulesAndPolicies.html",
"cssClass":"static-content rules-policies",
"menu":null
},
{
"id":"bonuses",
"leaf":true,
"description":"Sports Bonuses",
"link":"",
"content":"sportsBonuses.html",
"cssClass":"static-content",
"menu":null
}
]
},
{
"id":"conditions",
"leaf":false,
"description":"Terms & Conditions",
"link":"",
"content":"",
"cssClass":"",
"menu":[
{
"id":"termsOfService",
"leaf":true,
"description":"Terms of Service",
"link":"",
"content":"termsOfService.html",
"cssClass":"static-content",
"menu":null
},
{
"id":"privacy",
"leaf":true,
"description":"Privacy Policy",
"link":"",
"content":"privacy.html",
"cssClass":"static-content",
"menu":null
}
]
},
{
"id":"view",
"leaf":true,
"description":"View in: Mobile | Full Site",
"link":"",
"content":"view.html",
"cssClass":"static-content",
"menu":null
}
]
}

Pass the model variable to the function and then print it,
<li ng-repeat="submenu in menu.menu" id="{{submenu.id}}" class="{{submenu.cssClass}}">
<a ng-href="{{submenu.content}}" ng-click="ShowAlert(submenu)">{{submenu.description}}</a>
</li>
Controller.js
$scope.ShowAlert = function (val) {
$window.alert(val);
}
Demo
var app = angular.module("app", []);
app.controller("ListCtrl", ["$scope",
function($scope) {
$scope.ShowAlert = function (val) {
alert(val.content);
}
$scope.menus =
[{
"id": "contact",
"leaf": true,
"description": "Contact Us",
"link": "",
"content": "contactUs.html",
"cssClass": "static-content",
"menu": null
}, {
"id": "rules",
"leaf": false,
"description": "Sports Betting Rules",
"link": "",
"content": "",
"cssClass": "",
"menu": [{
"id": "types",
"leaf": true,
"description": "Wager Types",
"link": "",
"content": "wagerTypes.html",
"cssClass": "static-content wager-types",
"menu": null
}, {
"id": "odds",
"leaf": true,
"description": "Odds & Lines",
"link": "",
"content": "oddsAndLines.html",
"cssClass": "static-content",
"menu": null
}, {
"id": "policies",
"leaf": true,
"description": "Rules & Policies",
"link": "",
"content": "rulesAndPolicies.html",
"cssClass": "static-content rules-policies",
"menu": null
}, {
"id": "bonuses",
"leaf": true,
"description": "Sports Bonuses",
"link": "",
"content": "sportsBonuses.html",
"cssClass": "static-content",
"menu": null
}]
}, {
"id": "conditions",
"leaf": false,
"description": "Terms & Conditions",
"link": "",
"content": "",
"cssClass": "",
"menu": [{
"id": "termsOfService",
"leaf": true,
"description": "Terms of Service",
"link": "",
"content": "termsOfService.html",
"cssClass": "static-content",
"menu": null
}, {
"id": "privacy",
"leaf": true,
"description": "Privacy Policy",
"link": "",
"content": "privacy.html",
"cssClass": "static-content",
"menu": null
}]
}, {
"id": "view",
"leaf": true,
"description": "View in: Mobile | Full Site",
"link": "",
"content": "view.html",
"cssClass": "static-content",
"menu": null
}]
; // response data
}
]);
<!DOCTYPE html>
<html>
<head>
<link data-require="bootstrap#3.3.5" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<link data-require="bootstrap#3.3.5" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootswatch/3.3.5/cosmo/bootstrap.min.css" />
<link data-require="bootstrap#3.3.5" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />
<script data-require="jquery#1.11.3" data-semver="1.11.3" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script data-require="bootstrap#3.3.5" data-semver="3.3.5" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script data-require="angular.js#1.4.7" data-semver="1.4.7" src="https://code.angularjs.org/1.4.7/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app='app'>
<div ng-controller="ListCtrl">
<ul>
<li ng-repeat="menu in menus" id="{{artist.id}}">
<a ng-href="{{menu.content}}">{{menu.description}}</a>
<ul>
<li ng-repeat="submenu in menu.menu">
<a ng-href="{{submenu.content}}" ng-click="ShowAlert(submenu)">{{submenu.description}}</a>
</ul>
</li>
</ul>
</div>
</body>
</html>

Concerning $window.alert("{{menu.content}}");, Angular does not auto-magically evaluate expressions in all of JavaScript - it'll only evaluate expressions passed to it in templates. These get passed to something like $compile, which actually compiles the expression.
You can do something like this using $scope.$eval (which is not as evil as it sounds). That might look something like this:
var app = angular.module("app", []);
app.controller("ListCtrl", ["$scope", "$http", "$window",
function($scope, $http, $window) {
$http.get('menu.json')
.then(function(response) {
$scope.menus = response.data.menus; // response data
$scope.greeting = 'Hello, World!';
$scope.ShowAlert = function () {
var alert = $scope.$eval('menu.content')
$window.alert(alert);
}
});
}
]);
Alternatively, you could evaluate the expression inside of the HTML (which is what I would suggest, and what #Sajeetharan posted above, so I won't replicate it here).
Note that Angular 1.5+ discourages the use of controllers in this manner because they do not exist in this form in Angular 2.0. I'd highly recommend porting this code to use components instead. You'd have a few components; one for the ListCtrl, one for each menu, and one for each submenu.

Related

How can I render script tag with data block in PUG

I'm trying to paste a widget to my site. I'm currently using PUG as my template engine. I'm not sure how the syntax for a datablock should be written. Can someone help me point out what I'm doing wrong. Or maybe if there is a work around where I can call the async/data block in vanilla javascript?
I have already tried to add a . after the script tag still not working.
<!-- TradingView Widget BEGIN -->
<div class="tradingview-widget-container">
<div class="tradingview-widget-container__widget"></div>
<div class="tradingview-widget-copyright"><span class="blue-text">Financial Markets</span> by TradingView</div>
<script type="text/javascript" src="https://s3.tradingview.com/external-embedding/embed-widget-ticker-tape.js" async>
{
"symbols": [
{
"description": "BTC/THB",
"proName": "BXTH:BTCTHB"
},
{
"description": "ETH/THB",
"proName": "BXTH:ETHTHB"
},
{
"description": "XRP/THB",
"proName": "BXTH:XRPTHB"
},
{
"description": "EOS/THB",
"proName": "BITFINEX:EOSTHB"
},
{
"description": "LTC/THB",
"proName": "BITFINEX:LTCTHB"
},
{
"description": "BSV/THB",
"proName": "BITFINEX:BSVTHB"
}
],
"theme": "dark",
"isTransparent": false,
"displayMode": "adaptive",
"locale": "en"
}
</script>
</div>
<!-- TradingView Widget END -->
This is what I get from https://html2jade.org/.
// TradingView Widget BEGIN
.tradingview-widget-container
.tradingview-widget-container__widget
.tradingview-widget-copyright
a(href='https://www.tradingview.com', rel='noopener', target='_blank')
span.blue-text Financial Markets
| by TradingView
script(type='text/javascript', src='https://s3.tradingview.com/external-embedding/embed-widget-ticker-tape.js', async='')
{
"symbols": [
{
"description": "BTC/THB",
"proName": "BXTH:BTCTHB"
},
{
"description": "ETH/THB",
"proName": "BXTH:ETHTHB"
},
{
"description": "XRP/THB",
"proName": "BXTH:XRPTHB"
},
{
"description": "EOS/THB",
"proName": "BITFINEX:EOSTHB"
},
{
"description": "LTC/THB",
"proName": "BITFINEX:LTCTHB"
},
{
"description": "BSV/THB",
"proName": "BITFINEX:BSVTHB"
}
],
"theme": "dark",
"isTransparent": false,
"displayMode": "adaptive",
"locale": "en"
}
// TradingView Widget END
It seems like the html is correct. If you look at the screenshot

ionic ui-router resolve's result didn't show in the page

Here is the code
APP.js
.state('app.aboutus', {
url: '/aboutus',
views: {
'mainContent': {
templateUrl: 'templates/aboutus.html',
controller: 'AboutController',
resolve: {
leaders: ['corporateFactory', function(corporateFactory){
return corporateFactory.query();
}]
}
}
}
})
Controller.js
.controller('AboutController', ['$scope', 'leaders', 'baseURL', function($scope, leaders, baseURL) {
$scope.baseURL = baseURL;
$scope.showLeaders = false;
$scope.message="Loading ...";
$scope.leaders = leaders;
console.log($scope.leaders);
}])
Aboutus.html
<ion-view view-title="About Us">
<ion-content>
<div class="card">
<div class="list list-inset">
<div ng-repeat="leaders in leadership" class="item item-avatar item-text-wrap">
<h2>{{leaders.name}}</h2>
<h4>{{leaders.designation}}</h4>
</div>
</div>
</div>
</ion-content>
</ion-view>
db.json
"leadership": [
{
"id": 0,
"name": "Human 1",
"designation": "Chief Executive Officer"
},
{
"id": 1,
"name": "Human 2",
"designation": "Chief Food Officer"
},
{
"id": 2,
"name": "Human 3",
"designation": "Chief Taste Officer"
},
{
"id": 3,
"name": "Human 4",
"designation": "Executive Chef"
}
]
When I checked using inspect element - console tab in Google Chrome, the $resolved: has successfully changed from false into true, and every array contain the information per ID.
But, the data didn't show in the aboutus.html
Did I typed something wrong? or maybe I'm using a wrong method?
Thank you in advance!
Your problem is likely that your ng-repeat syntax is incorrect. Where you have leadership, that should be the object/array you're referencing in your scope. So try changing it to this:
<div ng-repeat="leader in leaders" class="item item-avatar item-text-wrap">
<h2>{{leader.name}}</h2>
<h4>{{leader.designation}}</h4>
</div>

Printing data using vm on Angular

I just started working on a new project which was started.
The last dev was using vm, and I need to print some data
Here I have the ctrl
(function () {
'use strict';
angular
.module('palpatine')
.controller('RotationsCtrl', RotationsCtrl);
/* #ngInject */
function RotationsCtrl (Rotations, $rootScope, $state) {
/*jshint validthis: true */
var vm = this;
vm.data = Rotations;
console.log(vm.data);
}
})();
than console.log(vm.data) returns an obj like this
[{
"_id": "5653e0fee890e41700946a75",
"name": "Mtg Rotation 112415 - SR",
"group": {
"_id": "563166b302d8831700dfc707",
"object_name": "rotation",
"name": "Mortgage",
"__v": 0,
"updated_on": "2015-10-29T00:22:11.868Z",
"created_on": "2015-10-29T00:22:11.868Z"
}, {
"_id": "5653e0fe946a75",
"name": "Mtg Rotation 112415 - JR",
"group": {
"_id": "700dfc707",
"object_name": "rotation 2",
"name": "Home Mortgage",
"__v": 7,
"updated_on": "2015-10-29T00:22:11.868Z",
"created_on": "2015-10-29T00:22:11.868Z"
}]
all I need is to render that data.name in an ul - li
let's say like this
<ul class="dropdown-menu" dropdown-menu>
<li ng-repeat="datum in vm.data.name">
{{datum}}
</li>
</ul>
what can I do ?
You should loop through a vm.data then print name from the each object like datum.name.
Markup
<ul class="dropdown-menu" dropdown-menu>
<li ng-repeat="datum in vm.data">
{{datum.name}}
</li>
</ul>

AngularJS rendering from deeply nested jsonp

I am new to JSON and also AngularJS. I'm trying to access data elements in a deeply nested remote json file. I can manage to render the whole JSON results in my view. However, I can't seem to target the elements that are in an array deep inside the JSON. It's from Yahoo Currency.
This is my controller and view that renders the entire JSON file:
controller
var app = angular.module('app', []);
app.controller('DataCtrl', function ($scope, $http) {
$http.jsonp('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fwebservice%2Fv1%2Fsymbols%2Fallcurrencies%2Fquote%3Fformat%3Djson%22&format=jsonp&callback=JSON_CALLBACK').success(function (data) {
$scope.data = data;
});
});
view
<!doctype html>
<html ng-app="app" >
<head>
<meta charset="utf-8">
<title>LIVE</title>
<!-- <link rel="stylesheet" href="style.css"> -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="DataCtrl">
<h1>Live from JSON feed</h1>
<ul>
<li ng-repeat="row in data">
{{ data }}
</li>
</ul>
</body>
</html>
I tried writing the controller like this:
var app = angular.module('app', []);
app.controller('DataCtrl', function ($scope, $http) {
$http.jsonp('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fwebservice%2Fv1%2Fsymbols%2Fallcurrencies%2Fquote%3Fformat%3Djson%22&format=jsonp&callback=JSON_CALLBACK').success(function (data) {
var pair = { name };
// $scope.data = data;
if(data) {
if (data.results) {
pair.name = data.results.list.resources[0].resource.fields.name;
}
}
});
});
But that doesn't work. Here is the JSON (partial) .. I'm trying to access the "name", "price", and "utctimestamp" fields for each resource:
{
"query": {
"count": 1,
"created": "2015-11-07T05:42:03Z",
"lang": "en-US",
"diagnostics": {
"publiclyCallable": "true",
"url": {
"execution-start-time": "0",
"execution-stop-time": "23",
"execution-time": "23",
"content": "http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json"
},
"user-time": "25",
"service-time": "23",
"build-version": "0.2.311"
},
"results": {
"list": {
"meta": {
"type": "resource-list",
"start": "0",
"count": "173"
},
"resources": [
{
"resource": {
"classname": "Quote",
"fields": {
"name": "USD/KRW",
"price": "1152.994995",
"symbol": "KRW=X",
"ts": "1446874620",
"type": "currency",
"utctime": "2015-11-07T05:37:00+0000",
"volume": "0"
}
}
},
{
"resource": {
"classname": "Quote",
"fields": {
"name": "SILVER 1 OZ 999 NY",
"price": "0.068046",
"symbol": "XAG=X",
"ts": "1446850711",
"type": "currency",
"utctime": "2015-11-06T22:58:31+0000",
"volume": "100"
}
}
},
{
"resource": {
"classname": "Quote",
"fields": {
"name": "USD/VND",
"price": "22364.000000",
"symbol": "VND=X",
"ts": "1446874620",
"type": "currency",
"utctime": "2015-11-07T05:37:00+0000",
"volume": "0"
}
}
},
...
For what it's worth, jsonp seems to return some kind of xml-looking stuff when I append the callback=JSON_CALLBACK to the url, like this:
JSON_CALLBACK({"query":{"count":"1","created":"2015-11-07T16:08:29Z","lang":"en-US"},"results":["<list><meta><type>resource-list</type><start>0</start><count>173</count></meta><resources><resource><classname>Quote</classname><fields><name>USD/KRW</name><price>1152.994995</price><symbol>KRW=X</symbol><ts>1446900900</ts><type>currency</type><utctime>2015-11-07T12:55:00+0000</utctime><volume>0</volume></fields></resource></resources><resources><resource><classname>Quote</classname><fields><name>SILVER 1 OZ 999 NY</name><price>0.068046</price><symbol>XAG=X</symbol><ts>1446850711</ts><type>currency</type><utctime>2015-11-06T22:58:31+0000</utctime><volume>100</volume></fields></resource></resources><resources><resource>
...
Is there a problem with how I'm using JSONp? I'm getting the data set rendered to my view (above) but it's all in the funky xml syntax. How to go about grabbing the 3 values I need from that to an array and rendering in a <ul>??
You can use your original controller, you only had problems in the view. It would work if you substitute it by this one:
<!doctype html>
<html ng-app="app" >
<head>
<meta charset="utf-8">
<title>LIVE</title>
<!-- <link rel="stylesheet" href="style.css"> -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="DataCtrl">
<h1>Live from JSON feed</h1>
<ul>
<li ng-repeat="res in data.query.results.list.resources">
{{ res.resource.fields.name }}: {{ res.resource.fields.price }}, {{ res.resource.fields.utctime }}
</li>
</ul>
</body>
</html>
Here is the Plunker using your JSON example: http://plnkr.co/edit/wzF5t9dTZt49n5eq9N1L?p=preview

Load JSON into Angular

I am new with Angular.js. I try to get json from my local url http://85.96.243.31/admin.productss/searchwithjson. JSON content is:
[
{
"fullsizeurl": "/uploads/incubout_denemeshop/1/product/3-kdd4eesv-erer-1-cent-1.png",
"productid": "3",
"price": "0.01",
"isactive": 1,
"brandid": "1",
"subcategoryid": "1",
"model": "1 Cent",
"isbundle": 0,
"subcategory": "Cat2",
"taxincluded": 0,
"brand": "erer",
"thumbnailsizeurl": "/uploads/incubout_denemeshop/1/product/3-kdd4eesv-erer-1-cent-1_thumb.png"
},
{
"productid": "1",
"isactive": 1,
"isbundle": 0,
"taxincluded": 0,
"thumbnailsizeurl": "/uploads/incubout_denemeshop/1/product/1-gu60axs2-erer-model-1_thumb.png",
"fullsizeurl": "/uploads/incubout_denemeshop/1/product/1-gu60axs2-erer-model-1.png",
"price": "15.00",
"brandid": "1",
"subcategoryid": "1",
"model": "model",
"subcategory": "Cat2",
"sku": "12",
"brand": "erer"
},
{
"fullsizeurl": "/uploads/incubout_denemeshop/1/product/4-sjy7xxyh-erer-qwert-1.png",
"productid": "4",
"price": "123.00",
"isactive": 1,
"brandid": "1",
"subcategoryid": "2",
"model": "qwert",
"isbundle": 0,
"subcategory": "Cat1",
"taxincluded": 0,
"brand": "erer",
"thumbnailsizeurl": "/uploads/incubout_denemeshop/1/product/4-sjy7xxyh-erer-qwert-1_thumb.png"
},
{
"productid": "2",
"price": "13.65",
"isactive": 1,
"brandid": "1",
"subcategoryid": "1",
"model": "yancı",
"isbundle": 0,
"subcategory": "Cat2",
"taxincluded": 0,
"brand": "erer"
}
]
Here is my code:
<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<body ng-app="MyApp">
<div ng-controller="PostsCtrl">
<ul ng-repeat="post in posts">
<li>{{post.fullsizeurl}}</li>
</ul>
</div>
<script>
var app = angular.module("MyApp", []);
app.controller("PostsCtrl", function($scope, $http) {
$http.get('http://85.96.243.31/admin.productss/searchwithjson').
success(function(data, status, headers, config) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
</script>
</body>
</html>
I couldn't get the fullsizeurls of products. What is the wrong with this code ?
I've tried your code and found out that the problem is in violating the rules of pulling data from different domain.
Are you sure you're pulling the JSON file from the same domain name where the html is being executed? - I've tried fetching your JSON file and storing with .html file and ran it perfectly fine from within the same folder.
If you fail to do, you'll be greeted with the following error in console log:
XMLHttpRequest cannot load http://localhost/searchwithjson. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Or as others suggest enable CROS (Cross-origin resource sharing) to be able to load JSON from different locations.

Categories