Simple angular example not working: ng-repeat + $resource + GET - angularjs

I am trying to iterate with ng-repeat, using data served from a REST service. I manage to recover the data in my main.js file, but I can't get the data to be injected into the HTML.
I just started learning nodejs and angular, so it is very probable that I am not clearly getting it. I am logging twice the call to the REST service, getting the data in one of them (using a callback function) and getting a promise in the other (Which I assume happens because the call is synchronous, I didn't use any callback function here).
What I don't understand is why the HTML doesn't get the data.
Anyway, here's the code:
main.js
var myApp = angular.module('myApp', ['ngResource']);
myApp.factory('restservice', function ($resource) {
var source = $resource(
"http://rest-service.guides.spring.io/greeting/");
var data =source.get({},function(){
//this log shows the data
console.log (data);
})
return data;
});
function AvengersCtrl($scope, $resource, restservice) {
$scope.servicedata = restservice;
//this log shows the promise
console.log($scope.servicedata);
}
index.html
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Tutorials</title>
<!-- <link rel="stylesheet" href="vendor/foundation/foundation.min.css"> -->
</head>
<body>
<div ng-app="myApp">
<div ng-controller="AvengersCtrl">
<input type="text" ng-model="search.$">
<table>
<tr ng-repeat="resource in servicedata | filter:search">
<td>{{resource.id}}</td>
<td>{{resource.content}}</td>
</tr>
</table>
</div>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular-resource.js"></script>
<script type="text/javascript" src="/angular/app/main.js"></script>
</body>
</html>
Thanks in advance, regards

The code looks good to me.
The problem is the service returns a Json object instead of list.
If you wrap it with a list like this, you will see the result
$scope.servicedata = [restservice];

Related

Data binding not working - AngularJS

Somehow, I am unable to display the data from my backend in the component. Console logging response.data gives me my data. I put it in the movies variable within the scope, but it doesn't bind. Here is the code:
INDEX.HTML FILE
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Movies - AngularJS</title>
<!-- Styles -->
<link rel="stylesheet" href="style.css">
<!-- Scripts -->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl" id="app">²
<div class="box" ng-repeat="movie in movies">
<h2 ng-class="movie.genre">{{ movie.genre }}</h2>
<h1>{{ movie.title }}</h1>
<p>Change the values of the movie.</p>
<input ng-change="onChange" ng-model="movie.title" type="text">
<input ng-change="onChange" ng-model="movie.genre" type="text">
</div>
</div>
<script src="main.js"></script>
</body>
</html>
MAIN.JS FILE
const app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
axios.get(`http://localhost:3001/api/movies`)
.then(response => {
$scope.movies = response.data;
console.log($scope.movies); // logs the data correctly
})
.catch(e => console.error(e.message));
});
I think it has something to do with Async/sync'ness but I don't know how to solve it. Thanks for the help! :)
Use angular $http instead of axios to make your requests since it will internally call for view digest when you update scope within callbacks
Any time you use code outside of angular context to update scope you need to tell angular to run a digest
Also will remove axios as unnecessary dependency to load in page since $http already exists in angularjs core
I do not see any issues with your code, probably you need to force the rendering manually using $scope.$apply();
$scope.movies = response.data;
$scope.$apply();
Since you are using axios and wrapping your angular $scope inside it, the digest cycle is unable to read that change
Use, angular's $http instead of axios
OR
If you want to use axios then, you can use $scope.$apply and wrap $scope.movies = response.data; inside it.
like
$scope.$apply(function () {
$scope.movies = response.data;
});
You need to tell angularjs to update - call
$scope.$evalAsync();
after set data

Angular http get no response from api

I am trying to get any information with Angular from the local api that I have created in Ruby, Sinatra platform. I am sure that the api is running on the port 4567 since I can see the data if i access m it directly through web interface. When I do that I see this (just next to the number 0 there is like a small arrow so it is possible to minimize the details of the object):
0
id "1"
name "Company-A21"
address "Gany-A11"
If I want to see RAW data I get this:
[{"id":"1","name":"Company-A21","address":"Gany-A11"}]
On the "other side" I am running apache2 and this HTML file:
<!doctype html>
<html >
<head>
<title>Hello AngularJS</title>
<script src="hello.js"></script>
</head>
<body>
<div ng-controller="Hello">
<p>The ID is {{company.id}}</p>
<p>The content is {{company.name}}</p>
</div>
</body>
</html>
And the hello.js:
angular.module('demo', [])
.controller('Hello', function($scope, $http){
$http.get('http://localhost:4567/api/v1/companies/2').
then(function(response) {
$scope.company = response.data;
});
});
Why I can not see response?
I just started to practice Angular and I stuck here...
Your data is an array of objects so you'd output it like: {{company[0].id}}
You probably followed an example using ng-repeat which would look something like this:
<div ng-repeat="company in companies">
<p>The ID is {{company.id}}</p>
<p>The content is {{company.name}}</p>
</div>
https://jsfiddle.net/ojzdxpt1/21/
Use ng-init to execute your get request. Implement your api call under a method:
angular.module('demo', [])
.controller('Hello', function($scope, $http){
$scope.getCompany = function(){
$http.get('http://localhost:4567/api/v1/companies/2').
then(function(response) {
$scope.company = response.data;
});
}
});
and use it in ng-init:
<!doctype html>
<html >
<head>
<title>Hello AngularJS</title>
<script src="hello.js"></script>
</head>
<body>
<div ng-controller="Hello" ng-init="getCompany()">
<p>The ID is {{company.id}}</p>
<p>The content is {{company.name}}</p>
</div>
</body>
</html>

trying it integrate prismic prismicio with angular js

Hey people i am trying to integrate prismic io with angular js 1 but it is not working.
I referred to many links to do that but i don't get anything data.
https://github.com/awulder/angular-prismicio
https://gist.github.com/laradevitt/94f7e21eaf6d3441b9475fc8f5201201
http://jsfiddle.net/othermachines/bbv9dzug/
and that's my code :
my code
app.js
// Define the `myApp` module
var app = angular.module('app', ['prismic.io']);
app.config(function(PrismicProvider) {
PrismicProvider.setApiEndpoint('https://myname.prismic.io/api');
PrismicProvider.setAccessToken('i put my access token');
PrismicProvider.setClientId('i used my id');
PrismicProvider.setClientSecret('i put my secret');
PrismicProvider.setLinkResolver(function(ctx, doc) {
return 'detail.html?id=' + doc.id + '&slug=' + doc.slug + ctx.maybeRefParam;
});
});
// Define the `AppCtrl` controller on the `app` module
app.controller('AppCtrl', ['Prismic', function(Prismic) {
var self = this;
Prismic.all().then(function(data) {
self.data = data;
});
}]);
index.html
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<script src="https://unpkg.com/prismic.io/dist/prismic.io.min.js"></script>
<script src="https://raw.githubusercontent.com/awulder/angular-prismicio/master/dist/angular-prismicio.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="AppCtrl">
<prismic-html fragment="data.fragment"></prismic-html>
<ul>
<li ng-repeat="item in data">
<span>{{item.slug}}</span>
</li>
</ul>
</body>
</html>
The idea with this Prismic thing is that it has the data on it and they are just providing some code for integration and then we read this json data using angular.
please if anyone used it before will be really nice to help.
thanks

Can I bind an AngularJS model to a hash URL and an HTML input at the same time?

I'm teaching myself Angular and I've looked over a number of examples that show how to bind a model to an HTML input so that they always contain the same text.
I understand that Angular also provides the $location service which works with the URL.
I have an application that I'm thinking of partially rewriting in Angular as a learning example.
In my example, I have an HTML input that I keep synced up with a model using jQuery and also synced up with a hash URL.
Is there a simple way of accomplishing this with AngularJS?
Consider the example application bellow:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/angular.js"></script>
<script>
var myApp = angular.module('myApp', []);
function FirstController($scope, $location) {
var data = {
bar: 'hello world'
};
$scope.data = data
}
</script>
</head>
<body>
<div ng-app="myApp">
<div ng-controller="FirstController">
<input ng-model="data.bar" />
<h2>{{ data.bar }}</h2>
</div>
</div>
</body>
</html>
This is a simple example showing how the model can be kept synced with a textbox. I was wondering if it's possible to keep it synced with a hash URL, as well, so that we would have http://www.example.com#bar=What_The_User_Typed
What you probably need is the $routeProvider
https://docs.angularjs.org/tutorial/step_07

Receive an array via $resource get method

Edited: Now this example fully works with external json service to see it in live
I can see the received array and params in the console.log, but I can't echo that array to the view...
That online JSON service returns {"key": "value"}
How to make this {{some_item.key}} to work? Thanks!!
<!DOCTYPE html>
<html ng-app="Simple">
<body>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.min.js"></script>
<div ng-controller="SimpleController">
{{some_item.key}}
</div>
<script>
angular.module('Simple', ['ngResource']);
function SimpleController($scope, $resource) {
$scope.simple = $resource('http://echo.jsontest.com/key/value',
{callback:'JSON_CALLBACK'},
{get:{method:'JSONP'}}
);
$scope.some_item = $scope.simple.get();
console.log($scope.some_item.key);
}
</script>
</body>
</html>
You need to put the interpolation inside the controller's scope like this
<div ng-controller="SimpleController">
{{some_item.key}}
</div>

Resources