Consuming REST service using AngularJS - angularjs

I have a REST Service written in Java which returns an array of data in JSON like this:
[{"key":"London","value":"51.30"}]
Now I'm trying code an AngularJS REST clients using the AJS documentation. So far I've been able to invoke the REST service (I can see from the server logs) yet nothing is printed in the HTML page.
Here is my code:
<!doctype html>
<html >
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-resource.js"></script>
<script language="javascript">
angular.module('myApp',['ngResource']);
function Ctrl($scope,$resource) {
var Geonames = $resource(
'http://localhost:8080/rest-application/rest/json', {
}, {
query: { method: 'GET', isArray: true },
create: { method: 'POST' }
}
);
$scope.objs = Geonames.query();
};
Ctrl.$inject = ['$scope','$resource'];
</script>
</head>
<body >
<div ng-app="myApp">
<div ng-controller="Ctrl">
{{objs.key}} - {{objs.value}}
</div>
</div>
</body>
</html>
I have tried this example with several small variants taken from tutorials yet it is still not working. Any help ?
Thanks!

What you get back from query() is an array so you should loop over it with ng-repeat
<div ng-app="myApp">
<div ng-controller="Ctrl">
<ul>
<li ng-repeat="obj in objs">{{obj.key}} - {{obj.value}}</li>
</ul>
</div>
</div>

First of all, let's organize your code a bit:
var app = angular.module('myApp',['ngResource']);
// Controllers get their dependencies injected, as long as you don't minify your code and lose variable names.
app.controller('Ctrl', function($scope, $resource) {
$scope.objs = []; // We initialize the variable for the view not to break.
// For the query example, you don't need to define the method explicitly, it is already defined for you.
var Geonames = $resource('http://localhost:8080/rest-application/rest/json');
// Resource methods use promises, read more about them here: http://docs.angularjs.org/api/ng/service/$q
Geonames.query({}, function(arrayResult) {
$scope.objs = arrayResult;
});
});
You have to adjust your html code with an ng-repeat directive to handle each item of your array:
<body>
<div ng-app="myApp">
<div ng-controller="Ctrl">
<!-- object is a reference for each item in the $scope.objs array-->
<span ng-repeat="object in objs">
{{object.key}} - {{object.value}}
</span>
</div>
</div>
</body>

Related

Angular Json Http Get - Not load

This is a simple test to fetch json file from third party server, but no success. I did test with this json (https://jsonplaceholder.typicode.com/posts) and is working. Any body can help me? Thanks in advance.
var app = angular.module("viewJSON",[]);
app.controller("viewCtrl",function Hello($scope, $http) {
$http.get('http://media.astropublications.com.my/api/drebar_landing.json').
success(function(data) {
$scope.testJer = data;
$scope.keys = Object.keys($scope.testJer[0]);
});
});
section {height:180px;}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<div ng-app="viewJSON" ng-controller="viewCtrl">
<div ng-repeat="item in testJer | filter:search">
<section class="col-md-3">
<h4>{{item.Title}}</h4>
<p>{{item.Description}}</p>
</section>
</div>
</div>
You need to access the ArticleObject array from the response ,
app.controller("viewCtrl", function Hello($scope, $http) {
$http.get('http://media.astropublications.com.my/api/drebar_landing.json').
success(function(data) {
$scope.testJer = data.ArticleObject;
});
});
PLUNKER DEMO

How to push an object array into an scop array?

In angular js How can I push an object array into an array.
Here is my code
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<h1 ng-repeat="x in records">{{x.Class}}
</h1>
<div ng-repeat="s in records.students">{{s.name}}</div>
<input ng-model="formdata.name" type="text" />
<input type="button" value="Save" ng-click="saveName(formdata)">
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.records = [{"Class":"Class 8"}];
$scope.saveName = function(name)
{
$scope.records.students.push({"name":name});
}
});
</script>
</body>
</html>
how can I push into $scope.records.students here $scope.records is an array.
what mistake I am doing I am getting "Cannot read property 'push' of undefined"
Your records property on $scope has no property called students. Therefore, $scope.records.students is undefined. Undefined doesn't have any methods available. You should make sure students exists before pushing.
Also, be aware the ngModel passes by reference. In your original code, the {{s.name}} list will only ever show the text in the input because each element in students points towards the same underlying reference. You should dereference the string that saveName receives. I've done so in the code below, but try playing with it so you can see how it works.
Updated code:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<h1 ng-repeat="x in records">{{x.Class}}
</h1>
<div ng-repeat="s in records.students">{{s.name}}</div>
<input ng-model="formdata.name" type="text" />
<input type="button" value="Save" ng-click="saveName(formdata)">
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.records = [{"Class":"Class 8"}];
$scope.saveName = function(name)
{
// Also, you need to derefence the object
// this is a quick and dirty way, try removing it and see
// what happens
var deRefName = JSON.stringify(name);
// Checks for the existence of students, if it doesn't exist
// sets students to an empty array
if (!($scope.records.students)) {
$scope.records.students = [];
}
$scope.records.students.push({"name":deRefName});
}
});
</script>
</body>
</html>
As the error denotes, there is no way you can access records.students since its an array, not an object.
You need to have records as either an object and inside it student as an array.
then you should be able to access $scope.records.students.
or use $scope.records as array and use index to access the particular object of it.

Play Framework + Angular Issue with JSON render on Page

I have simple Scala Play Framework and Angular application. I tried to render JSON data on play's "xxx.scala.html" template but don't know what is the problem it is not rendering as expeted.
#main("Welcome to Play") {
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"> </script>
<script>
app.controller('NamesCtrl', function($scope) {
// get names using AngularJS AJAX API
$http.get('/getNames').success(function(data){
$scope.names = data;
});
});
</script>
<div ng-app="app" ng-contoller="NamesCtrl">
<ul>
<li ng-repeat=" name in names">{{name}}</li>
</ul>
</div>
}
My route entry
GET /getNames controllers.HomeController.getNames
Scala Controller:
def getNames = Action {
val names = List("Bob","Mike","John")
Ok(Json.toJson(names)).as(JSON)
}
When I am calling my page using url
http://localhost:9000/getNames
I was getting response on page as below,
["Bob","Mike","John"]
Please can you explain what am I doing wrong here?
Thanks !!
There are some problems in the code. The correct one is this:
#main("Welcome to Play") {
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.19/angular.min.js"></script>
<div ng-app="myApp" ng-controller="NamesCtrl">
<ul>
<li ng-repeat="name in names">{{name}}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('NamesCtrl', function($scope, $http) {
$http.get('/getNames').success(function(data){
console.log(data);
$scope.names = data;
});
});
</script>
}
What has changed:
AngularJS 1.3.19 instead of 1.2.10
AngularJS module - which is referenced in the div
injected the $http service in the controller
your ng was wrong - it should be ng-controller instead of ng-contoller (a typo I guess)
The result is what you would expect:

angular ng-click add http data inside ng-repeat

I use $http.get php data in ng-repeat is correct,but I have a problem when ng-click to add push php second page data in ng-repeat ,but it not work .
Any suggestions ? thanks.
I did not write very clear , i mean when click button , i want get ats01.php?page=2 data, add ats01.php?page=1 data in li ng-repeat, i don't want get page2 data replace page1 data,just like jquery $('#ul01').append (html) method; thank your answer it .
script.js
var scotchApp = angular.module('scotchApp');
var myurl="http://192.168.5.9/"
scotchApp.controller('mainController', function($scope, $http) {
$http.get(myurl+"php/ats01.php?page=1")
.success(function (response) {$scope.names = response.records;});
$scope.myur=myurl;
$scope.add = function() {
$http.get(myurl+"php/ats01.php?page=2")
.success(function (response) {
$scope.names.push(response.records);
});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html >
<head >
<script src="anjs/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="scotchApp" >
<div ng-controller="mainController">
<ul >
<li ng-repeat="x in names track by $index">
<p > <small>{{x.TA002}} {{x.TA003}} {{x.TA004}} {{x.TA012}}</small> </p>
</li>
</ul>
<p> <button ng-click="add()">Add</button> </p>
</div>
</body>
</html>
For first time you are assigning record in the list
$scope.names = response.records;
But in click you are pushing same data instead of assigning
$scope.names.push(response.records);
If you push instead of assign it'll create a index and push whole data into that index.
Convert this
$scope.names.push(response.records);
to this
$scope.names=$scope.names.concat(response.records);

nicEdit doesn't work in templates

I'm trying to add the wysiwyg nicEdit text editor to my text areas. When I goto the actual templateUrl the textbox and tool bar do work but they do not submit correctly (to my firebase db). When I goto the page that is to render the template I am unable to get get nicEdit toolbar features and just get a regular text area box. I'm using angularjs and have the templateurl as addPost.html.
So again the template does render when I goto #/addPost but not with the working nicEdit features, yet going directly to the template url addPost.html does have the nicEdit features working but then won't submit to my firebase db. Anyone have an idea on why this is so? Thanks.
Template file addPost.html:
<head>
<script type="text/javascript" language="javascript" src="../nicEdit.js"></script>
<script type="text/javascript" language="javascript">
bkLib.onDomLoaded(nicEditors.allTextAreas);
</script>
<!-- Bootstrap core CSS -->
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
<nav class="blog-nav">
<a class="blog-nav-item " href="#/welcome">Home</a>
<a class="blog-nav-item active" href="#/addPost">Add Post</a>
<a class="blog-nav-item " style="cursor:pointer;" ng-click="logout();">Logout</a>
</nav>
</head>
<body ng-controller="AddPostCtrl">
<div class="container" >
<form class="form-horizontal" ng-submit="AddPost()">
<fieldset>
<!-- Form Name -->
<legend>Create Post</legend>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-4 control-label" for="txtPost">Post</label>
<div class="col-md-4">
<textarea class="form-control" id="txtPost" ng-model="article.post" name="txtPost" ></textarea>
</div>
</div>
</fieldset>
</form>
</div><!-- /.container -->
</body>
addPost.js
'use strict';
angular.module('myApp.addPost', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/addPost', {
templateUrl: 'addPost/addPost.html',
controller: 'AddPostCtrl'
});
}])
.controller('AddPostCtrl', ['$scope','$firebase','$location','CommonProp',function($scope,$firebase, $location,CommonProp) {
if(!CommonProp.getUser()){
$location.path('/main');
}
$scope.logout = function(){
CommonProp.logoutUser();
}
$scope.AddPost = function(){
var title = $scope.article.title;
var date = $scope.article.date;
var post = $scope.article.post;
var firebaseObj = new Firebase("http://..");
var fb = $firebase(firebaseObj);
fb.$push({ title: title, date: date, post: post,emailId: CommonProp.getUser() }).then(function(ref) {
console.log(ref);
$location.path('/welcome');
}, function(error) {
console.log("Error:", error);
});
}
}]);
Going to #addPost shows the template with out nicEdit working
But going to the actual templateUrl addPost.html it works fine, minus not being able to submit
The problem has to do with trying to run scripts Angular html partials. The simple solution is to move the scripts you need to the head of your main index file, outside of ng-view, though it does seem (according to other stackoverflow posts) technically possibly to try to get these scripts to execute:
"AngularJS: How to make angular load script inside ng-include?"
https://stackoverflow.com/a/19715343/1078450
(Also, you have html in your head file that is not likely to be rendered: <nav class="blog-nav">)
Well, I have had the same problem, with initialisation of NicEdit in templates.
First I used onDomLoaded() else, but it's better to wait for the document. With jQuery I use document.ready.
Take a look here, pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
The problem is to tell NicEditor the new textarea.
Here a code sample to do this in jQuery.
var idnr = 0;
var NicEditor = new nicEditor();
$('#add').click(function(){
var $clone = $('#dummy').clone();
var id = 't_' + idnr;
idnr = idnr + 1;
$clone.attr('id',id).attr('name',id).removeClass('dummy');
$('#wrapper').append($clone);
NicEditor.panelInstance(id);
$(nicEditors.findEditor(id).elm).focus();
});
And here is a working Example of dynamic NicEdit use.

Resources