So I made a simple Angular - nvd3 project. I'm using liveData.example from this Github Library (angularjs-nvd3-directives). I improve it a little bit in order to use my REST API.
This is my REST API:
http://amr2.mybluemix.net/getmet/list
And this is my code:
<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<title>Angular.js nvd3.js Live Data Chart Example</title>
<meta http-equiv="content-type" content="text/html; charset=UTF8">
<script src="js/angular.js"></script>
<script src="js/d3.js"></script>
<script src="js/nv.d3.js"></script>
<script src="js/moment.js"></script>
<script src="dist/angularjs-nvd3-directives.js"></script>
<link rel="stylesheet" href="nv.d3.css"/>
<script>
var app = angular.module("nvd3TestApp", ['nvd3ChartDirectives']);
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
app.factory('DataMeterDetail', ['$http', function($http){
var getData = function(_id, _rev){
return $http({
method: 'JSONP',
url: 'http://amr2.mybluemix.net/getmet/list'
});
}
return{
getDataDetail: function(_id, _rev){return getData(_id, _rev);}
}
}]);
app.factory('DataMeter', function(){
return {
cityId: 0,
units: 'imperial'
}
});
function ExampleCtrl($scope, DataMeterDetail, DataMeter){
function fetchData(){
DataMeterDetail.getDataDetail(5506956, 'imperial')
.success(function(response){
console.log(response);
var dta = [{key:"100010001_20082015_0", values:[]}];
dta[0].values = response.list.map(function(d){
return [d._id, d._rev];
});
$scope.exampleData = dta;
});
}
fetchData();
$scope.xAxisTickFormatFunction = function(){
return function(d){
return d3.time.format('%x-%H:%M')(new Date(d*1000));
}
}
}
</script>
<style>
div{
font-family: sans-serif;
}
</style>
</head>
<body ng-app='nvd3TestApp'>
<div ng-controller="ExampleCtrl">
<input type="text" ng-model="cityName"/>
<div>Example Data</div> </div>
<nvd3-line-chart
data="exampleData"
id="exampleId"
width="800"
height="400"
showXAxis="true"
showYAxis="true"
tooltips="true"
interactive="true"
xAxisTickFormat="xAxisTickFormatFunction()"
margin="{left:100,top:20,bottom:20,right:10}"
yAxisLabel="Temperature (F)"
xAxisLabel="Date"
>
<svg></svg>
</nvd3-line-chart>
</div>
</body>
</html>
Now the code doesn't work. Can you guys show me whats wrong with this code?
Thanks in advance.
Maybe this can help to solve that problem..
I had encountered the same problem above that you mentioned.
My code snippets are below .
Just use $scope.apply in timer function ..
setInterval(function(){
$scope.$apply(function(){
// var data= $scope.exampleData;
$scope.exampleData = data;
// console.log( 'Client ON ### setInterval called!! ' , $scope.exampleData[0].values[0]);
});
}, 200); // 0.2 sec
Related
This is the code that I want to work out, it's about AMap.com geolocation API. I want to know how to get this value (such as gLats in code) out of the function onComplete().
<!DOCTYPE html>
<html>
<head>
<title>amap</title>
<meta charset="utf-8">
<link rel="stylesheet" href="http://cache.amap.com/lbs/static/main1119.css"/>
<script type="text/javascript" src="http://webapi.amap.com/maps?v=1.3&key=key"></script>
<script type="text/javascript" src="http://cache.amap.com/lbs/static/addToolbar.js"></script>
</head>
<body>
<div id='container'></div>
<div id="tip"></div>
<div id="text"></div>
<div id="txt"></div>
<script type="text/javascript">
var map, geolocation;
map = new AMap.Map("", {
resizeEnable: true
});
map.plugin('AMap.Geolocation', function() {
geolocation = new AMap.Geolocation({
});
map.addControl(geolocation);
geolocation.getCurrentPosition();
AMap.event.addListener(geolocation, 'complete', onComplete);
AMap.event.addListener(geolocation, 'error', onError);
});
function onComplete(data) {
var str=['succsee'];
var gLngs=data.position.getLng();
var gLats=data.position.getLat();
str.push('longitude:' + data.position.getLng());
str.push('latitude:' + data.position.getLat());
document.getElementById('tip').innerHTML = str.join('<br>');
document.getElementById('text').innerHTML = str.join('<br>');
}
function onError(data) {
document.getElementById('tip').innerHTML = 'failure';
}
</script>
</body>
</html>
As I can see, you are already accessing the needed values in onComplete():
str.push('longitude:' + data.position.getLng());
str.push('latitude:' + data.position.getLat());
You cannot simply get them, onComplete is a callback that is called when the values are available. So do anything about them in onComplete, you may want to assingn them to global variables, etc, to have them easyly accessible from anywhere in code.
Assigning them to globals is the way to go.
//declare in the global scope
var gLats = null;
var gLngs = null;
...
function onComplete(data)
{
var str=['success'];
gLats=data.position.getLat();
gLngs=data.position.getLng();
...
}
When i try to run the below example mentioned in the Angular JS timer site, I am getting error:
ng:areq
Bad Argument
Argument 'MyAppController' is not a function, got undefined
http://errors.angularjs.org/1.3.14/ng/areq?p0=MyAppController&p1=not%20a%20function%2C%20got%20undefined
at Error (native)
at file:///C:/ICDP/Angular/angular/angular.min.js:6:417
at Sb (file:///C:/ICDP/Angular/angular/angular.min.js:19:510)
at tb (file:///C:/ICDP/Angular/angular/angular.min.js:20:78)
at file:///C:/ICDP/Angular/angular/angular.min.js:75:331
at file:///C:/ICDP/Angular/angular/angular.min.js:57:65
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Example - Multiple Timers Example</title>
<script src="../angular/angular.min.js"></script>
<script src="../app/js/timer.js"></script>
<script>
angular.module('MyApp', ['timer']);
function MyAppController($scope) {
$scope.timerRunning = true;
$scope.startTimer = function (){
$scope.$broadcast('timer-start');
$scope.timerRunning = true;
};
$scope.stopTimer = function (){
$scope.$broadcast('timer-stop');
$scope.timerRunning = false;
};
}
MyAppController.$inject = ['$scope'];
</script>
</head>
<body ng-app="MyApp">
<div ng-controller="MyAppController">
<h2>AngularJS - Multiple Timers Example</h2>
<h3>Timer 1: <timer/></h3>
<h3>Timer 2: <timer interval="2000"/></h3>
<h3>Timer 3: <timer> minutes, seconds.</timer></h3>
<button ng-click="startTimer()" ng-disabled="timerRunning">Start Timers</button>
<button ng-click="stopTimer()" ng-disabled="!timerRunning">Stop Timers</button>
</div>
</body>
</html>
I have the below two files included
<script src="../angular/angular.min.js"></script>
<script src="../app/js/timer.js"></script>
http://siddii.github.io/angular-timer/examples.html#/plain-javascript-source
Open Chrome developer tools(F12), then open folder with file: angular-timer -> examples -> angularjs-single-timer.html and you will see that (it is just little mistake):
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Example - Single Timer Example</title>
<!-- compiled JavaScript -->
<script type="text/javascript" src="../dist/assets/js/angular-timer-bower.js"></script>
<script type="text/javascript" src="../dist/assets/js/angular-timer-all.min.js"></script>
<script>
angular.module('MyApp', ['timer'])
.controller('MyAppController', ['$scope', function ($scope) {
$scope.timerRunning = true;
$scope.startTimer = function (){
$scope.$broadcast('timer-start');
$scope.timerRunning = true;
};
$scope.stopTimer = function (){
$scope.$broadcast('timer-stop');
$scope.timerRunning = false;
};
$scope.$on('timer-stopped', function (event, data){
console.log('Timer Stopped - data = ', data);
});
}]);
</script>
</head>
<body ng-app="MyApp">
<div ng-controller="MyAppController">
<h1>AngularJS - Single Timer Example</h1>
<h3><timer/></h3>
<button ng-click="startTimer()" ng-disabled="timerRunning">Start Timer</button>
<button ng-click="stopTimer()" ng-disabled="!timerRunning">Stop Timer</button>
</div>
<br/>
</body>
</html>
You have not MyAppController Controller. You must tell angular that there is controller named MyAppController. Try this to fix your problem.
angular.module('MyApp', ['timer']).controller('MyAppController', MyAppController);
And link that can be useful https://docs.angularjs.org/guide/controller
I would like to open a new tab after $http call. Currently, even-though the call is made after user click, popup blocker doesn't allow new tab to be created.
HTML:
<div ng-controller="ExampleController">
<button ng-click="openNewTab()">Open new tab</button>
</div>
Controller
.controller('ExampleController', ['$scope','$http', function($scope,$http) {
$scope.openNewTab = function(e) {
$http.get("test.com").finally(()=>{
window.open();
});
};
}]);
Plunker
Try this Code to open the new tab call the function
.controller('ExampleController', ['$scope','$http', function($scope,$http,$window) {
$scope.openNewTab = function(e) {
$http.get("test.com").finally(()=>{
$window.open('url','_blank');
});
};
}]);
You can use setInterval out of ajax call where you have to check your variable again and again which will be set in ajax call when condition matches then you can open new tab.
I've also found a workaround for you.
<!DOCTYPE html>
<html ng-app="Demo">
<head>
<meta charset="utf-8" />
<title>Demo</title>
<script data-require="jquery#2.0.1" data-semver="2.0.1" src="http://code.jquery.com/jquery-2.0.1.min.js"></script>
<script src="https://code.angularjs.org/1.3.0-beta.9/angular.js"></script>
<script src="demo.js"></script>
</head>
<body ng-controller="DemoCtrl">
<button ng-click="doesntWork()">This Doesn't Work</button>
</body>
</html>
and the angular code:
angular.module("Demo", []).controller("DemoCtrl", function($scope, $http) {
$scope.doesntWork = function() {
var isSuccess=0;
$http.get('https://api.github.com/users/angular').then(function (result)
{
isSuccess=1;
});
var timer = setInterval(function () {
if (isSuccess!= 0) {
clearInterval(timer);
}
if (isSuccess== 1) {
var newWin = $window.open('', '_blank');
newWin.location = "https://www.google.co.in";
}
},1000);
};
});
You can do this by using the $window service. $window is a wrapper around the global browser object window. Maybe this solves your answer too:
Open a new tab on button click in AngularJS
I've also found a workaround for you.
<!DOCTYPE html>
<html ng-app="Demo">
<head>
<meta charset="utf-8" />
<title>Demo</title>
<script data-require="jquery#2.0.1" data-semver="2.0.1" src="http://code.jquery.com/jquery-2.0.1.min.js"></script>
<script src="https://code.angularjs.org/1.3.0-beta.9/angular.js"></script>
<script src="demo.js"></script>
</head>
<body ng-controller="DemoCtrl">
<button id="test" ng-click="works()">This Works</button>
<button ng-click="doesntWork()">This Doesn't Work</button>
</body>
</html>
and the angular code:
angular.module("Demo", []).controller("DemoCtrl", function($scope, $http) {
function openInNewTab() {
var uri = 'http://www.google.nl';
var link = angular.element('');
angular.element(document.body).append(link);
link[0].click();
link.remove();
};
$("#test").click(function(){
openInNewTab();
});
$("#test").click();
$scope.works = openInNewTab;
$scope.doesntWork = function() {
$http.get('https://api.github.com/users/angular').then(openInNewTab);
};
});
Please have a look at the following code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Using Javascript</title>
<meta http-equiv="author" content="infinite_999">
<link rel="stylesheet" type="text/css" href="css.css">
</head>
<body>
<div id="name"></div>
<div id="rooms"></div>
<div id="booked"></div>
<div id="available"></div>
<script src="javascript.js"></script>
</body>
</html>
Javascript:
var hotel={
//Properties
name:'Pacific Idea',
rooms:20,
booked:15,
//Methods
checkAvailability = function () {
return this.rooms- this.booked;
}
};
var nameHotel=document.getElementById('name');
var roomHotel=document.getElementById('rooms');
var bookedHotel=document.getElementById('booked');
var availableHotel=document.getElementById('available');
nameHotel.textContent=hotel.name;
roomsHotel.textContent=hotel.rooms;
bookedHotel.textContent=hotel.booked;
availableHotel.textContent=hotel.checkAvailability();
Now according to this code, the name, number of booked rooms, number of available rooms of the hotel should be displayed. But unfortunately, it just doesn't display anything.
Please help me..
2 errors in your javascript code. one is checkAvailability = function (); should be ':' instead of '='. and roomsHotel typo error.
Try
var hotel={
//Properties
name:'Pacific Idea',
rooms:20,
booked:15,
//Methods
checkAvailability : function () {
return this.rooms- this.booked;
}
};
var nameHotel=document.getElementById('name');
var roomsHotel=document.getElementById('rooms');
var bookedHotel=document.getElementById('booked');
var availableHotel=document.getElementById('available');
nameHotel.textContent=hotel.name;
roomsHotel.textContent=hotel.rooms;
bookedHotel.textContent=hotel.booked;
availableHotel.textContent=hotel.checkAvailability();
I am trying to implement module pattern in my code according to some examples online, what I am trying to achieve is to simply bind a button click event in my html to a function (which is not working), below is my HTML:
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#*" data-semver="1.3.7" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js"></script>
<script data-require="jquery#*" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<h1>Hello Plunker!</h1>
<input type="button" id="btn-msg" value="click me"/>
</body>
</html>
and here is my JS:
//CRUD Start
var Rutherford = Rutherford || {};
Rutherford.crud = function() {
function _readLists() {
alert("am here");
}
return {
readLists: _readLists
}
}
Rutherford.Initiate = function() {
$("#btn-msg").click(Rutherford.crud.readLists);
}
$(function() {
Rutherford.Initiate();
});
Here is as well a link to my plunker: http://plnkr.co/edit/tA94lzMPHkUOr8QuyJK8?p=preview
All what am trying to achieve is to bind the button to the function.
You need to call the anonymous function, not assign it. See the () below:
Rutherford.crud = (function() {
function _readLists() {
alert("am here");
}
return {
readLists: _readLists
}
}());
Here's an updated plunkr with this change: http://plnkr.co/edit/uiWHmtkMFEKywvFRk6DF?p=info
I believe that Evan Knowles wanted to say this:
//CRUD Start
var Rutherford = Rutherford || {};
Rutherford.crud = (function() {
function _readLists() {
alert("am here");
}
return {
readLists: _readLists
}
})( );
Rutherford.Initiate = function() {
$("#btn-msg").click(Rutherford.crud.readLists);
}
$(function() {
Rutherford.Initiate();
});
This would work properly if you can use Rutherford as a Singleton.