How to use angular ng-repeat with an Web api? - javascript

I'm trying to build a website using front-end html and get its data from a Web-api. My Web-api returns a json format. So I was trying to use the Get request using Angular $http and ng-repeat directive. My angular controller is like this -
'use strict'; app.controller('blogsController', ['$scope','$http', function ($scope, $http) {
$http.get('www.example.com/api/blog')
.then(function(res){
$scope.blogs = res.data;
});
}]);
The html code looks like this -
<body app="ng-app" >
<div ng-repeat="xr in blogs" >
<div id="blog_title" >
{{xr.blog_title}}
</div>
<div id="blog_text">
{{xr.blog_text}}
</div>
</div>
</body>
I have tried this but this is not getting me the data from the blog web api.
Please help me to get the solution.....

there is nothing wrong in your code
<div ng-repeat="xr in blogs" >
<div id="blog_title" >
{{xr.blog_title}}
</div>
<div id="blog_text">
{{xr.blog_text}}
</div>
</div>
but make sure that your res.data must follow an arrangement like below:
res.data = [{'blog_title': 'title value1', 'blog_text':'text value'}
{'blog_title': 'title value2', 'blog_text':'text value'}
{'blog_title': 'title value3', 'blog_text':'text value'}]
print your res.data in web console using console.log to confirm.

You are missing ng-controller on the template, and app should be ng-app
<body ng-app="ng-app" ng-controller="blogsController">
<div ng-repeat="xr in blogs" >
<div id="blog_title" >
{{xr.blog_title}}
</div>
<div id="blog_text">
{{xr.blog_text}}
</div>
</div>
</body>

Related

AngularJS not printing variable

I'm currently building my first single page app with angularJS. The variable information stored in my controller is not displaying on the page. After extensively trying to trouble-shoot this I am at a loss to why it isn't displaying.
<div ng-repeat="x in pers" class="person">
<div class="name">{{ pers.person }}</div>
<div class="out">Out</div>
<div class="in" >In</div>
<div class="onsite">On site</div>
<div class="notes">
<div class='n'></div>
<div class='dn'>Delete note</div>
<div class='an'>Add note</div>
</div>
My controller looks like this.
app.controller("MainController", ['$scope', function($scope) {
$scope.pers = [
{
person: 'Nick',
},
{
person: "Greg",
}];
}]);
The repeat function works as expected and two tables are formed, however both the divs with the class name are left without any text in them on the page. I have tried using ng-binding="pers.person" as well without any success.
Thanks in advance for any help you can offer with this issue I'm having.
it should be {{x.person}}
you are using ng-repeat of pers with the alias x

Angularjs and routeParams

I have a piece of code that is getting JSON data from a local server. I am trying to display those data into a page and then when i'll click on a product i want to see the details of it. So far i can display all my products into a page but when i'm heading to the details page i got an error Cannot read property 'id' of undefined. Can you please help me out?
This is my code so far.
app.js
'use strict';
angular.module('app', []).
config(function($routeProvider){
$routeProvider.
when("/", {templateUrl: "/partials/products.html"}).
when("/details/:id", {templateUrl: "/partials/details.html", controller: DetailsCtrl}).
otherwise({redirectTo: "/"});
})
function AppCtrl($scope, $http){
$http.get('http://localhost:3000/api/products/727617361726372')
.success(function(data){
$scope.productList = data;
/*$scope.filterProductsByCategory = function(category){
$scope.search = category
};*/
})
.error(function(data){
console.log("Error!: ");
});
}
function DetailsCtrl($scope, $routeParams){
$scope.item = $scope.productList[$routeParams.id];
}
details.html
<h2>This is the details pages</h2>
product id: {{ item.product_id }}
<br/>
product name: {{ item.product_name}}
index.html
<div class="container" ng-app="app" ng-controller="AppCtrl">
<h1 class="text-danger">Welcome to our Store</h1>
<hr/>
<ng-view></ng-view>
</div>
products.html
<div class="col-lg-4 col-sm-6 col-xs-12" ng-repeat="product in productList">
<div class="thumbnail">
<img src="img/img3.jpeg">
<div class="caption">
<h4>{{ product.product_name }}</h3>
<p>Category: {{ product.category_name }} ({{ product.category_id }})</p>
<p class="text-muted">{{ product.product_details}}</p>
<ul class="list-inline">
<li>
<p class="product-price btn">€ {{ product.product_price }}</p>
</li>
<li>
Add to Cart
</li>
</ul>
</div>
</div>
Thanks!!!
you are getting the productList in your AppCtrl. If you want to access a specific item in your DetailsCtrl you'll need to get the specific item since you can't access AppCtrl scope variables in another Ctrl.
The best way to do this would be to create an extra rest call for getting a single item.
A quick way to fix your code, although I really don't recommend it would be to use $rootcope in your AppCtrl
I'd suggest reading Angular Docs on $scope. It might give you a better understanding how scopes work in angular:
https://docs.angularjs.org/guide/scope#!
I assume you have injected ngRoute correctly.
angular.module('app', ['ngRoute'])
Other than that there is nothing wrong with your code.
Demo
Just check your code again.

AngularJS Dynamic Template with indexed scope variable arrays

I'm using AngularJS and trying to create a form where I can dynamically add new inputs, similar to this fiddle: http://jsfiddle.net/V4BqE/ (Main HTML below, working code in fiddle).
<div ng-app="myApp" ng-controller="MyCtrl">
<div add-input>
<button>add input</button>
</div>
</div>
I would like to be able to use a HTML template for my form since the input I'm adding is ~300 lines long. My issue is I cannot figure out how to index the scope variable containing the data when used in a template. I've tried to make my own modified version of the above code on plnkr http://plnkr.co/edit/4zeaFoDeX0sGTuBMCQP2?p=info . However, when I click the button no form elements appear.
Online (plnkr) I get a 404 not found for my template.html, but I think that is just a plnkr limitation. On my machine with a Python HttpServer I get an Error: [$parse:syntax] for the $templateRequest and a TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. when using the $http.get method.
Any advice for getting the indexed scope variable array to work with an external html file?
Thanks, JR
Edit: Update plnkr link
You can do it without directive & external template
what you are trying to do does not require a directive (it actually much simple with the basic angularjs tools)
http://plnkr.co/edit/LVzGN8D2WSL2nR1W7vJB?p=preview
html
<body>
<div class="container" ng-app="myApp" ng-controller="MyCtrl">
<button class="btn btn-primary" type="button" ng-click="addPhoneInput()">add input</button>
<form>
<div ng-repeat="item in telephoneNumbers">
<hr>
<input type="text" ng-model="item.phone">
</div>
</form>
<hr>
<div class="well">
<h4>Phone Numbers,</h4>
<p ng-repeat="item in telephoneNumbers">{{item.phone}}</p>
</div>
</div>
</body>
js
var app = angular.module('myApp', []);
app.controller('MyCtrl', ['$scope', function($scope) {
// Define $scope.telephone as an array
$scope.telephoneNumbers = [];
$scope.addPhoneInput = function() {
$scope.telephoneNumbers.push({});
};
// This is just so you can see the array values changing and working! Check your console as you're typing in the inputs :)
$scope.$watch('telephoneNumbers', function(value) {
console.log(value);
}, true);
}]);
If you insist using a directive,
http://plnkr.co/edit/BGLqqTez2k9lUO0HZ5g1?p=preview
phone-number.template.html
<div>
<hr>
<input type="text" ng-model="ngModel" >
</div>
html
<body>
<div class="container" ng-app="myApp" ng-controller="MyCtrl">
<button class="btn btn-primary" type="button" ng-click="addPhoneInput()">add input</button>
<form>
<phone-number ng-repeat="item in telephoneNumbers" ng-model="item.phone"></phone-number>
</form>
<hr>
<div class="well">
<h4>Phone Numbers,</h4>
<p ng-repeat="item in telephoneNumbers">{{item.phone}}</p>
</div>
</div>
</body>
js
var app = angular.module('myApp', []);
app.controller('MyCtrl', ['$scope', function($scope) {
// Define $scope.telephone as an array
$scope.telephoneNumbers = [];
$scope.addPhoneInput = function() {
$scope.telephoneNumbers.push({});
};
// This is just so you can see the array values changing and working! Check your console as you're typing in the inputs :)
$scope.$watch('telephoneNumbers', function(value) {
console.log(value);
}, true);
}]);
app.directive('phoneNumber', function(){
return {
replace:true,
scope: {
ngModel: '=',
},
templateUrl: "phone-number.template.html"
}
});

Books Won't Display for Reader App Exercise

I'm trying to get books to display based on the assignment above but can't figure out what is wrong for the life of me.
I built the service and modified the controller and view pages to the point where I believe they should display the books in the view, but I'm just seeing a blank page.
I feel like I am probably not retrieving the data properly and accessing it in the view/html.
Any ideas? Link to jsFiddle.
Index.html
<body ng-app="ReaderApp">
<div class="header">
<div class="container">
Reader
</div>
</div>
<div class="main">
<div class="container">
<div ng-view></div>
</div>
</div>
<!-- Modules -->
<script src="js/app.js"></script>
<!-- Controllers -->
<script src="js/controllers/BookshelfController.js"></script>
<script src="js/controllers/BookController.js"></script>
<script src="js/controllers/ChapterController.js"></script>
<!-- Services -->
<script src="js/services/books.js"></script>
</body>
js/apps.js
var app = angular.module('ReaderApp', ['ngRoute']);
app.config(function($routeProvider){
$routeProvider
.when('/books', {
controller: 'BookshelfController',
templateUrl: 'views/bookshelf.html'
})
.otherwise({
redirecTo: '/books'
});
});
js/services/books.js
app.factory('books', ['$http', function($http) {
return $http.get('https://s3.amazonaws.com/codecademy-content/courses/ltp4/books-api/books.json')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
js/controllers/BookshelfController
app.controller('BookshelfController', ['$scope', 'books', function($scope, books) {
books.success(function(data) {
$scope.myBooks = data;
});
}]);
js/views/bookshelf.html
<div class="bookshelf row">
<!--
TODO: Loop through myBooks and display each one with this HTML
<div class="book col-md-3">
<a href="#/books/{{$index}}">
TODO: Add the book's cover here
<h3 class="title"> </h3>
<p class="author"> </p>
</a>
</div>
-->
<div class="book col-md-3" ng-repeat="book in myBooks">
<a href="#/books/{{$index}}">
<img ng-src="{{ book.cover }}">
<h3 class="title">{{ book.title }}</h3>
<p class="author">by {{ book.author }}</p>
</a>
</div>
</div>
I think I had the same trouble and my problem was in the router. Try adding array brackets ( [ ] ) and the '$routeProvider' string in your config method (app.js) like this:
app.config(['$routeProvider', function($routeProvider) {
// Normal router stuff goes here
}]);
Coming from Ember, the syntax is a little weird so I've been using this tutorial as reference when I get stuck.

Template is compiled before the result is returenf from $http service

Hi I am trying to retrieve data from the server using $http, and correct data is being retrieved from the service, the data is -
[{
"URL":"someimg.jpg",
"TITLE":"Test Demo",
"DATE_ADDED":"2014-02-08 00:46:00",
"SUMMARY":"this is summary"
}]
the template that I wrote is as follows -
<article class="span8" ng-controller="allBlogs">
<div ng-show="success">
<div ng-repeat="blog in blogs.data">
<div class="row">
<div class="span3">
<img ng-src="{{blog['URL']}}" alt="" />
</div>
<div class="span5" ng-repeat-end>
<h4>{{blog.TITLE}}</h4>
<p>{{blog.DATE_ADDED}}</p>
<p>{{blog.SUMMARY}}</p>
</div>
</div>
</div >
</div>
</article>
the controller for the above template is as follows -
pk.controller("allBlogs", function($scope, $http, BlogsHandler){
$scope.success = false;
(function(){
BlogsHandler.getAllBlogs().success(function(data){
console.log(data);
$scope.success = true;
$scope.blogs = data.data;
});
})();
});
I am trying to set the success as true when the service returns data and thus the remaining part of the template should run. But this is not happening. Is it not that any change to $scope variable is being watched by the framework itself?
Help needed. I even tried with ng-switch with no effect.
Thanks
You assign data.data to $scope.blogs, so you don't need to add .data before blogs again.
$scope.blogs = data.data;
So, try this:
<div ng-repeat="blog in blogs track by $index">
<div class="row">
<div class="span3">
<img ng-src="{{blog.URL}}" alt="" />
</div>
<div class="span5">
<h4>{{blog.TITLE}}</h4>
<p>{{blog.DATE_ADDED}}</p>
<p>{{blog.SUMMARY}}</p>
</div>
</div>
</div >

Categories

Resources