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 >
Related
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>
I want to repeat data using div and in this div , I have one more repeatation using id value from first repeatation. So I want to pass this value using function in ng-init but got me error.
<div ng-controller="ProductsCtrl" ng-init="getData()">
<div class="col-sm-12" ng-repeat="data in form">
<div class="card">
<div class="card-header">
<h4>{{data.title}}</h4>
</div>
<div class="card-block">
<div class="row" ng-init="getImages({{data.id}})">
<div class="form-group col-sm-3" ng-repeat="image in images">
<figure>
<img ng-src="{{imgURL}}/{{image.file_name}}" width="220" height="176">
<figcaption>Fig.1 - A view of the pulpit rock in Norway.</figcaption><br />
<label>Description : {{image.remarks}}</label><br />
Read More . .
</figure>
</div>
</div>
</div>
<div class="card-footer">
<h4>{{data.description}}</h4>
</div>
</div>
</div>
</div>
So, how can I pass {{data.id}} in ng-init="getImages({{data.id}})"? If I put value ng-init="getImages(15)" then, item will appear.
file.js
$scope.getImages = function (id2) {
$http.get(commonData.apiURL + 'product/detailsImage.php?id='+id2)
.success(function (data) {
$scope.images = data;
//console.log(JSON.stringify(data));
})
.error(function (data, status, headers, config) {
$scope.errorMessage = "Couldn't load the list of Orders, error # " + status;
console.log("error");
});
}
You need to keep one thing in mind, If you are want your angular code to work on html page, use {{}}. And you do not need these curly braces if you are writing the code with the angular attributes... It means if something is already part of angularjs, you need not to use curly braces.
To solve this issue, you need to replace the below line
<div class="row" ng-init="getImages({{data.id}})">
with this following line
<div class="row" ng-init="getImages(data.id)">
You do not need annotations {{}}
ng-init="getImages(data)
and then inside the controller
$scope.getImages = function(data){
console.log(data.id);
}
I'm working on a blog like structured web app In AngularJS. Im trying to retrieve the user which is an other of a post and retrieve their display name dynamically as it loops through all the posts but I cant seem to retrieve data correctly.. This is what I have done so far.
Blog Controller:
uno.controller('newsCtrl', function($scope, $http, adbFactory){
$scope.derp = 'derp!!!!!';
adbFactory.get($http, 'get users 1', false).success(function(data){
$scope.user = data;
}).error(function(){
console.log('Errorrr');
});
$scope.init = function(){
adbFactory.get($http, 'get all blog_posts', true).success(function(data){
$scope.posts = data;
console.log($scope.posts);
});
};
$scope.getAuthor = function(_id) {
adbFactory.get($http, 'get users id ' +_id+ ' spec', false).success(function(data){
//$scope.author = data;
//console.log($scope.author);
return data;
});
};
});
If I console.log the data it shows the users perfectly given the author id which is in the database, but when i attempt to call the getAuthor function using the '{{ }}' scope i get a collage of errors... heres my blog template below.
Blog Template:
<div class="large-12 small-12 columns" ng-init="init()">
<div class="row">
<div class="large-12 small-12 columns" ng-repeat="topic in posts" style="margin-bottom:20px;">
<div id="news-post" class="panel animated fadeInUp">
<div class="row" ng-init="getAuthor(topic.author_id)">
<div class="large-2 small-2 columns">
<img src="{{ topic['thumb'] }}" alt="" style="border-radius:50%; height:100px; width: 150px;" />
</div>
<div class="left large-10 small-10 columns">
<div class="row">
<h2 class="post-title">{{topic['title']}} <p>Posted By, {{ getAuthor(topic.author_id).email }}</p></h2>
<p>{{ topic['body'] }}</p>
</div>
</div>
</div>
</div>
</div>
<hr>
</div>
</div>
not quite sure what the problem can be.. Any thing I'm missing?
UPDATE::
I recently updated my controller and factories to get a better scope of handling my data flow, my Controller now looks like this:
uno.controller('newsCtrl', function($scope, $http, adbFactory, $cacheFactory, unoFunctions){
$scope.init = function(){
adbFactory.get($http, 'get all blog_posts', true).success(function(data){
$scope.posts = data;
$scope.getUser = function(_id) {
$scope.userData = unoFunctions.getUser(_id);
//console.log($scope.userData);
return $scope.userData;
};
});
$scope.getTags = function(_id) {
var post = unoFunctions.getPost(_id);
var _tags = post.tags.split(',');
for(var i = 0; i < _tags.length; i++)
{
_tags[i] = _tags[i].trim();
}
return _tags;
};
$scope.getUserName = function(_id) {
$scope.userData = unoFunctions.getUser(_id);
return $scope.userData.display_name;
};
$scope.getUser = function(_id) {
$scope.userData = unoFunctions.getUser(_id);
//console.log($scope.userData);
return $scope.userData;
};
$scope.getUserName = function(_id) {
$scope.userData = unoFunctions.getUser(_id);
return $scope.userData.display_name;
};
};
});
the unoFunctions factory is wht I use now to handle certain requests from my database, and that is shown below.
uno.factory('unoFunctions', function(adbFactory, $http, $cacheFactory){
var fact = {};
var user = $cacheFactory('user');
var post = $cacheFactory('post');
fact.getUser = function(_id) {
if(!user.get(_id)){
adbFactory.get($http, 'get users id '+_id+' spec', false).success(function(data){
user.put(_id, data);
});
}
return user.get(_id);
};
fact.getPost = function(_id) {
if(!post.get(_id))
{
adbFactory.get($http, 'get blog_posts id '+_id+' spec', false).success(function(data){
post.put(_id, data);
});
}
return post.get(_id);
};
fact.loggedIn = function()
{
console.log('gfdg');
};
/*------------------------------*/
return fact;
});
And my template to output the result is this:
<div class="large-12 small-12 columns" ng-init="init()">
<div class="row">
<div class="large-12 small-12 columns" ng-repeat="topic in posts | filter:postTitle | orderBy:'-time' " style="margin-bottom:20px;">
<div id="news-post" class="panel animated fadeInUp" ng-init="getTags(topic.id)">
<div class="row" style="padding-bottom:0px;">
<div class="large-2 small-2 columns">
<img src="{{ topic['thumb'] }}" alt="" style="border-radius:50%; height:120px; width: 200px;" />
</div>
<div class="left large-10 small-10 columns">
<div class="row" style="padding-bottom:0px;">
<h2 class="post-title">
<a href="#/news/post/{{ topic['id'] }}">
{{topic['title']}}
</a>
<p style="font-size:13px; font-style:italic; color:#a5a5a5" class="right">{{ topic.time | timeago }} {{ }}</p>
<p style="font-weight:bold; font-style:italic; color:#aaa">Posted By, {{ getUser(topic.author_id).display_name }}</p></h2>
<p>{{ topic['body'] }}</p>
<div ng-repeat="tag in getTags(topic.id)"><span style="background:#ccc; margin:7px; padding:4px; border-radius:5px; font-size:12px" class="left">{{ tag }}</span></div>
<p class="right" style="background:#dedede; font-size:13px; padding:7px; border-radius:6px; color:#1985A1;">{{ topic.category }}</p
</div>
</div>
</div>
</div>
</div>
</div>
</div>
This works fine and returns the required results I'm looking for but I wish to get rid of the countless Error: [$rootScope:infdig] errors and keep my console clean.. I researched the error and it seems to be because when I call functions from the unoFunctions factory like, getUser, or getPost. it returns a new array each time or something like that which I guess throws things out of scope. I'm not entirely sure, and reason for this?
This binding
<p>Posted By, {{ getAuthor(topic.author_id).email }}</p>
assumes that getAuthor returns an object, but it doesn't, even with proper return statement - because asynchronous request takes place, and adbFactory chain will apparently return a promise, not an object. And doing adbFactory.get every time getAuthor bindings are being watched would be bad performance-wise - json result has to be parsed constantly, even with $http cache.
A suitable solution for caching and binding service results to the scope (and a precursor to full-blown model) is
var authors = $cacheFactory('authors');
$scope.getAuthor = function(_id) {
if (!authors.get(_id)) {
authors.put(_id, {});
adbFactory.get($http, 'get users id ' +_id+ ' spec', false).success(function(data){
authors.put(_id, data);
});
}
return authors.get(_id);
};
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.
I'm trying to paginate my blogroll using AngularJS and the MEAN Stack. I have my Articles (blog posts) controller set up, and I've list.html to display everything. I can either get all the blogs to display, or I can get the pagination to increment, but I can't get the blogroll to show 5 items at a time and increment with the pagination.
angular.module('mean.articles')
.controller('ArticlesController', ['$scope', '$routeParams', '$location', 'Global', 'Articles', function ($scope, $routeParams, $location, Global, Articles) {
$scope.global = Global;
$scope.currentPage = 0;
$scope.pageSize = 5;
//I've my create, update and delete methods here.
$scope.find = function() {
Articles.query(function(articles) {
$scope.articles = articles;
});
};
$scope.numPages = function() {
return Math.ceil($scope.Articles.length / $scope.pageSize);
};
And here's my list.html:
<div class="container" style="width:900px; margin:auto">
<div class="container" style="width:600px; float:left">
<section data-ng-controller="ArticlesController" data-ng-init="find()">
<ul class="articles unstyled" style="width:600px">
<li data-ng-repeat="article in articles | filter:search | limitTo:pageSize">
<h2><a data-ng-href="#!/articles/{{article._id}}">{{article.title}}</a></h2>
<div>{{article.content}}</div>
<div>{{article.tags}}</div>
<h4><small>
<div class="well well-small text-center" style="width:300px">
<div style="margin:auto">
<span>{{article.created | date:'medium'}}</span> /
<span>{{article.user.name}}</span>
</div>
</div>
</small></h6>
</li>
</ul>
<h1 data-ng-hide="!articles || articles.length">No articles yet. <br> Why don't you Create One?</h1>
<button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">
Previous
</button>
{{currentPage+1}}/{{numPages()}}
<button ng-disabled="currentPage >= numPages()-1" ng-click="currentPage=currentPage+1">
Next
</button>
</section>
</div>
<div class="container" style="width:300px; float:left">
<input type="text" ng-model="search" placeholder="Enter your search terms" />
</div>
http://jsfiddle.net/2ZzZB/56/ from Pagination on a list using ng-repeat. It looks like the main thing you're missing is a way to indicate where to start your ng-repeat. The fiddle I linked to solves it by creating a startFrom filter.