Refresh JSON Data Using Angular - javascript

Just finished a Codeacademy tutorial using angular to loop through some JSON data from a URL and display the data.
Would love to know how to implement it so the data would be updated if the JSON data was changing periodically!
I know I need to maybe refresh the http get request,but after that I'm not sure.
If someone could point me in the right direction I would really appreciate it!
Thanks!
services/forecast.js
app.factory('forecast', ['$http', function($http) {
return $http.get('http://json-time.appspot.com/time.json')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
controllers/MinorController.js
app.controller('MinorController', ['$scope', 'forecast', function($scope, forecast) {
var setTimeOut = setInterval(function () {
forecast.success(function(data) {
$scope.fiveDay = data;
});
}, 5000);
$scope.$on('$routeChangeStart', function (scope, next, current) {
if (next.$$route.controller != "MinorController") {
clearInterval(setTimeOut); // clear interval here
}
});
}]);
test.html (view)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Angular -->
<script src="js/shared/angular.min.js"></script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="css/bootstrap.min.css">
<!-- Bootstrap JS -->
<script src="js/shared/bootstrap.min.js"></script>
</head>
<body ng-app="myApp">
<div class="container" ng-controller="MinorController">
<div class="row">
<h1>Time JSON Example</h1>
<h2>{{ fiveDay.tz }} </h2>
<h2> {{ fiveDay.hour }} </h2>
<h2> {{ fiveDay.datetime }} </h2>
<h2> {{fiveDay.second }} </h2>
</div>
</div>
<!-- Modules -->
<script src="js/app.js"></script>
<!-- Controllers -->
<script src="js/controllers/MainController.js"></script>
<script src="js/controllers/MinorController.js"></script>
<!-- Services -->
<script src="js/services/forecast.js"></script>
</body>
</html>

You can do it by using setInterval like so.
app.controller('MinorController', ['$scope', 'forecast', function($scope, forecast) {
var setTimeOut = setInterval(function () {
forecast.success(function(data) {
$scope.fiveDay = data;
});
}, 5000);
$scope.$on('$routeChangeStart', function (scope, next, current) {
if (next.$$route.controller != "MinorController") {
clearInterval(setTimeOut); // clear interval here
}
});
}]);
Now your service will call every 5 seconds and rebind your object.
If you go to another screen, then the routeChangeStart event will call for the interval to be cleared.

You can do it on several ways:
You can make http request in loop every few seconds
setInterval(function(){ alert("Hello"); }, 3000);
If you develop server data source you can setup real time connection, using i.e. SignalR or Socket

Related

ngClick event not fire after html binding

I binded html data from angular js post to Html div, but not ng click is fired in the binding html content.
This is my binding html div.
<div ng-app="SupportManagement">
<div ng-controller="SupportCtrl">
<div ng-click="openModal(5)"></div>
<div id="detailBlock"></div>
</div>
</div>
This my bind function with Angularjs Post
angular.module("SupportManagement", [])
.controller("SupportCtrl", function ($scope, $http) {
$scope.openModal = function (ticketId) {
$http.get('SupportDetail.aspx?ticketId='+ticketId).then(function (response) {
$("#detailBlock").html(response.data);
},
function (error) {
alert("fail");
alert(error);
}
);
}
$scope.openTicketHistory=function(){
var id= $('#tckId').attr('prob');
$http.post('SupportDetail.aspx/ShowHistory',
{ ticketId: id }).then(function (success) {
alert("success")
}
);
}
});
The place is I call the openTicketHistory function inside detailBlock div. And not firing the ngClick event. What can I do?
Check This Out
<html lang="en" >
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Angular Material style sheet -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.8/angular-material.min.css">
</head>
<body ng-app="BlankApp" ng-cloak>
<div>
<div ng-controller="SupportCtrl">
<div id="detailBlock">{{myWelcome}}</div>
<md-button ng-click="openModal(5)">Test</md-button>
</div>
</div>
<!-- Angular Material requires Angular.js Libraries -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-animate.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-aria.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-messages.min.js"></script>
<!-- Angular Material Library -->
<script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.8/angular-material.min.js"></script>
<!-- Your application bootstrap -->
<script type="text/javascript">
/**
* You must include the dependency on 'ngMaterial'
*/
angular.module('BlankApp', ['ngMaterial', 'ngMessages'])
.controller("SupportCtrl", function ($scope, $http) {
$scope.openModal = function (ticketId) {
$http.get('SupportDetail.aspx?ticketId='+ticketId)
.then(function (response) {
$("#detailBlock").html(response.data);
},
function (error) {
alert("fail");
alert(error);
}
);
}
$scope.openTicketHistory=function(){
var id= $('#tckId').attr('prob');
$http.post('SupportDetail.aspx/ShowHistory',
{ ticketId: id }).then(function (success) {
alert("success")
});
}
});
</script>
</body>
</html>
<!--
Copyright 2016-2018 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that can be found in the LICENSE file at https://material.angularjs.org/latest/license.
-->
First, here are some best practices
You should not access the DOM from your controller, don't try to think like Jquery where you have to access the DOM element in order to update it (See conceptual overview chapter from angularjs docs)
Avoid using $scope in your controller, use "controller as syntax instead"
Avoid using $http inside your controller, use an angularjs service instead
As for the solution, you can just use Angularjs's Data binding feature to bind the model (inside the Controller) to the view
$scope.ticket = response.data
in the view:
<div id="detailBlock">{{ticket}}</div>
Here is the link to a working jsfiddle : http://jsfiddle.net/bhjd4kto/25/
EDIT :
if your goal is to display html content inside #detailBlock, you can use angular-sanitize and ng-bind-html directive, here is an example : http://jsfiddle.net/bhjd4kto/45/

Why is there no response data and why are variables unresolved in my AngularJS app?

What is wrong here? I've scoured StackOverflow, read Angular and PHP manuals, and attempted to use some code that other people used, and still nothing has solved the problem.
I cannot figure out why there is no response data and why the {{user.variable_names}} are unresolved, nothing is showing up when I run the code. I have debugged as much as possible, but still not luck.
MarketController.js
var OrchidApp = angular.module('OrchidApp', ['ui.router', 'ngCookies']);
OrchidApp.controller('MarketController', function ($http, $scope) {
$http.get('market.php')
.then(function (response) {
$scope.users = response;
});
});
Market.php
<?php
include 'dbConfig.php';
$sel = mysqli_query($con,"select * from Chef");
if (!$sel) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
$data = array();
while ($row = mysqli_fetch_array($sel)) {
$point = array("fullname"=>$row['fullname'],"city"=>$row['city'],"state"=>$row['state'],"zip_code"=>$row['zip_code'],"rating"=>$row['rating']);
array_push($data, $point);
}
echo json_encode($data);
index.html
<!doctype html>
<html lang="en" data-ng-app="OrchidApp">
<head>
<meta charset="utf-8">
<base href="/">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Orchid</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body class="container">
<div>
<table>
<tr ng-repeat="user in users" data-ng-controller="MarketController">
<td>{{user.fullname}}</td>
<td>{{user.city}}</td>
<td>{{user.state}}</td>
<td>{{user.zip_code}}</td>
<td>{{user.rating}}</td>
</tr>
</table>
</div>
<!-- Libraries -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-cookies.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.4.2/angular-ui-router.min.js"></script>
<!-- App Scripts -->
<script src="../server.js"></script>
<script src="../marketControllers.js"></script>
<script src="../dbHelpers/market.php"></script>
</body>
</html>
If this is your plain code, you are missing, at least, the angular bootstrap. In other words you need to initialize your angular app by automatic or manual process.
If you want automatic initialization, just put something like this in your html tag:
<html ng-app="optionalModuleName" ng-strict-di>
Or if you want to do it manual, you can do this:
angular.module('myApp', [])
.controller('MarketController', ['$scope', function ($scope) {
...
}]);
angular.element(function() {
angular.bootstrap(document, ['myApp']);
});
Also, you should check if the response exists or not so you don't get unexpected results
Check here for more info about bootstrap angular:
https://docs.angularjs.org/guide/bootstrap
Your response is the response.object, if you want to get the body, you have to use the data-Property like this:
var OrchidApp = angular.module('OrchidApp', ['ui.router', 'ngCookies']);
OrchidApp.controller('MarketController', function ($http, $scope) {
$http.get('market.php')
.then(function (response) {
$scope.users = response.data;
});
});

How to get data from rest api which has basic authentication?

I'm trying to get data from this website through HTTP get method. This website has basic authentication. The data is in JSON format.
This is the rest api website:
(https://shoploapi.herokuapp.com/sellers)
// Code goes here
angular.module('myapp', ['myapp.controller']);
angular.module('myapp.controller', ['myapp.service'])
.controller('testController', function($scope, testService) {
$scope.posts = {};
function GetAllPosts() {
var getPostsData = testService.getPosts();
getPostsData.then(function(post) {
$scope.posts = post.data;
}, function() {
alert('Error in getting post records');
});
}
GetAllPosts();
});
angular.module('myapp.service', [])
.service('testService', function($http) {
//get All NewsLetter
this.getPosts = function() {
return $http.get('https://shoploapi.herokuapp.com/sellers');
};
});
angular.module('myApp', ['base64'])
.config(function($httpProvider, $base64) {
var auth = $base64.encode("bhupendra7:ice123age456");
$httpProvider.defaults.headers.common['Authorization'] = 'Basic ' + auth;
});
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.5.0" data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-base64/2.0.5/angular-base64.js"></script>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body ng-app="myapp">
<h1>Hello Plunker!</h1>
<div ng-controller="testController">
<div>
<ul>
<li ng-repeat="post in posts">
{{post.careof}} {{post.district}} {{post.gender}} {{post.name}}
</li>
</ul>
</div>
</div>
</body>
</html>
Here's the link to my Plunker:
(https://plnkr.co/edit/7pqljm?p=preview)
Can anyone help?
There are 2 problems in your code.
1. You have a typo
In angular.module('myApp', ['base64']), change to module name to myapp
2. The way you have injected your myapp.controller to myapp module
Change it to angular.module('myapp', []); You will also need to reorder your code. Check out the Plunker I have created for you.
Even if you fix the above two problems, you will still face a CORS problem from Heroku. Depending on your server-side technology (NodeJS, Rails etc.), you will need to enable it from the server to be able to communicate with your app. You can also look in to JSONP with AngularJS
Hope this helps

REST call in AngularJS does not display record

This is my first AngularJS project. I followed this website to create a simple html to display a single record by calling restful services. The rest works with the url "http://localhost:8080/api/seqs/fdebfd6e-d046-4192-8b97-ac9f65dc2009".
Here is my html:
<html ng-app="cgApp" ng-controller="CgseqCtrl">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular-resource.js"></script>
<script src="../js/controller.js"></script>
</head>
<body>
<div>
<hr>
<h2>{{seq.analysisId}}</h2>
<h2>{{seq.library}}</h2>
</hr>
</div>
</body>
</html>
I defined the resource in a service js
//service.js
angular.module('cgApp', ['ngResource'])
.factory('CgseqService', function ($resource) {
return $resource('http://localhost:8080/api/seqs/fdebfd6e-d046-4192-8b97-ac9f65dc2009',
{get: {method: 'GET'}
});
});
The controller:
//controller.js
angular.module('cgApp', ['ngResource'])
.controller('CgseqCtrl', ['CgseqService', '$scope', function (CgseqService, $scope)
{
$scope.getSeq = function(response) {
CgseqService.get(function(data) {
$scope.seq = data;
});
};
}]);
When I started my http server with Node.js and typed the url in the browser, nothing is displayed. What did I do wrong?
Several errors.
You didn't load your factory code. It looks like you only loaded your controller.js (I'm assuming your factory code is in a different file since in your example you commented it as //service.js):
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular-resource.js"></script>
<script src="../js/controller.js"></script>
</head>
np-controller should say ng-controller:
<html ng-app="cgApp" np-controller="CgseqCtrl">
You also never called your $scope.getSeq function:
$scope.getSeq = function(response) {
CgseqService.get(function(data) {
$scope.seq = data;
});
};
You should call $scope.getSeq() somewhere to actually invoke it.

html page can not find angular

I have the below code in a html page, running it though I keep getting an error stating that "angular is not defined" I have included angular in the head so i'm not sure why it can't locate it, the url to angular i'm also able to hit directly.
<!DOCTYPE>
<html ng-app="test">
<head>
<title>
<script src="https://code.angularjs.org/1.2.25/angular.js"></script>
</title>
</head>
<body ng-controller="TestController">
<form name="CopyFile" ng-submit="copy(fileId)">
<input type="text" ng-model="fileId"/>
<input type="submit" value="Copy"/>
</form>
<div>{{ message }}</div>
<div>{{ error }}</div>
<script type="text/javascript">
(function () {
var app = angular.module("test", []);
var testController = function ($scope, $http) {
$scope.copy = function (fileId) {
$http.get("http://localhost/test/copy/prod.aspx/ToProd?fileId=" + fileId)
.then(onComplete, onError);
};
var onComplete = function (response) {
$scope.message = response;
};
var onError = function (reason) {
$scope.error = "File could not be copied " + reason;
};
};
app.controller("TestController", ["$scope", "$http"], testController);
} ());
</script>
</body>
</html>
This may not be the cause but you don't want your angular include inside of your title. It should be something more like this:
<!DOCTYPE>
<html ng-app="test">
<head>
<title>My Page</title>
<script src="https://code.angularjs.org/1.2.25/angular.js"></script>
</head>
.....
You gave <script> inside <title>?
<title>
<script src="https://code.angularjs.org/1.2.25/angular.js"></script>
</title>
Please remove it outside.

Categories

Resources