ng-src not resolving image path stored in MongoDB - javascript

This is my code in my view
<div ng-controller="HomeController">
<div class="row">
<div class="col-xs-12 col-sm-offset-1 col-sm-3">
<div class="media">
<div class="media-top media-middle">
<a ui-sref="#">
<img class="media-object img-thumbnail" ng-src="{{dish.image}}" alt="MENU" >
</a>
<div class="media-body">
<h2 class="media-heading" style="color:red">This is Hot/Featured</h2>
</div>
</div>
</div>
</div>
</div>
This is my controller
.controller('HomeController', ['$scope', 'menuFactory', function($scope, menuFactory) {
menuFactory.getDishes().query(
function(response) {
var dishes = response;
$scope.dish= dishes[0];
},
function(response) {
$scope.message='Error' + response.status+ " " + response.statusText;
});
}])
.controller('HomeController', ['$scope', 'menuFactory', function($scope, menuFactory) {
menuFactory.getDishes().query(
function(response) {
var dishes = response;
$scope.dish= dishes[0];
},
function(response) {
$scope.message='Error' + response.status+ " " + response.statusText;
});
}])
This is my Service.js code
.service('menuFactory', [/*'$http'*/ '$resource', 'baseURL', function(/*$http*/ $resource, baseURL) {
this.getDishes = function(){
return $resource(baseURL+"dishes",null, {'get':{method:'GET' }}); //$http.get(baseURL+"dishes");
};
}])
I have checked the path, it does exist. When I give the path directly, the image is displayed. When the above code is used, it is not. When I check in console, ng-src keyword itself doesn't get displayed. But the same code works in other machine which is my laptop. I think there is some dependency issue. Please help.

Related

Doesn't display the object in view/html angular

I'm learning MEAN , i'm trying to display information from object, it has 2 arrays, it semms is working because I can see the object with console log of Javascript but it doesn't showing in html.
My code from javascript (books.js)
var myApp = angular.module('myApp');
myApp.controller('BooksController', ['$scope', '$http', '$location', '$routeParams',function($scope, $http, $location, $routeParams){
console.log("BooksController loaded");
$scope.getBooks = function(){
$http.get('/api/books')
.then(function(response){
console.log(response)
$scope.books = response;
});
}
}]);
My code from html (book.html)
<div class="panel panel-default" ng-init="getBooks()">
<div class="panel-heading">
<h3 class="panel-title">Latest Books</h3>
</div>
<div class="panel-body">
<div class="row">
<div ng-repeat="book in books">
<div class="col-md-3">
<div class="col-md-6">
{{book.title}}
<p>
{{book.description}}
</p>
</div>
<div class="col-md-6">
<img src="{{book.image_url}}" />
</div>
</div>
</div>
</div>
</div>
</div>
Image of getting data with console
Screenshot of object
Question is I can't figure out how to solve it, because it doesn't display in book.html.
Screenshot of book.html
I hope someone can help me.
Thanks for your help.
Your problem is the assignment of the response - it should be:
$scope.books = response.data;
Notice how in your console you have to expand data to see your array - because your response is an object, containing data as a key with your array.
You need to assign it the value of response.data
var myApp = angular.module('myApp');
myApp.controller('BooksController', ['$scope', '$http', '$location', '$routeParams',function($scope, $http, $location, $routeParams){
console.log("BooksController loaded");
$scope.books = '';
$scope.getBooks = function(){
$http.get('/api/books')
.then(function(response){
console.log(response)
$scope.books = response.data;
});
}
}]);

Dynamically display comments with links inside using Angular JS

i have developed a comment system using Angular JS. Unfortunately if a user inserts a link in his comment, the link is not clickable in the displayed comment.
How can i achieve this ?
Here is my HTML code:
<section class="comment-list" ng-hide="loading" ng-repeat="comment in comments">
<article class="row">
<div class="col-md-2 col-sm-2 hidden-xs">
<figure class="thumbnail">
<img class="img-responsive" src="#{{ comment.user.avatar }}" />
</figure>
</div>
<div class="col-md-10 col-sm-10" style="padding-bottom: 10px;">
<div class="comment_panel panel-default arrow left">
<div class="panel-body">
<header class="text-left">
<div class="comment-user"><i class="fa fa-user"></i> #{{ comment.user.name }}</div>
<time class="comment-date"><i class="fa fa-clock-o"></i> #{{ comment.date }}</time>
</header>
<div class="comment-post">
<p ng-bind-html="sanitizedComment"></p>
</div>
</div>
</div>
</div>
</article>
The comment body is inside the #{{ comment.comment.content }}
Here is the angular controller:
angular.module('mainCtrl', [])
// inject the Comment service into our controller
.controller('mainController', function($scope, $http, $sce, Comment) {
// object to hold all the data for the new comment form
$scope.commentData = {};
$scope.sanitizedComment = $sce.trustAsHtml($scope.comment.comment.content);
// loading variable to show the spinning loading icon
$scope.loading = true;
// get all the comments first and bind it to the $scope.comments object
// use the function we created in our service
// GET ALL COMMENTS ==============
Comment.get()
.success(function(data) {
$scope.comments = data;
$scope.loading = false;
});
// function to handle submitting the form
// SAVE A COMMENT ================
$scope.submitComment = function() {
$scope.loading = true;
// save the comment. pass in comment data from the form
// use the function we created in our service
Comment.save($scope.commentData)
.success(function(data) {
// if successful, we'll need to refresh the comment list
Comment.get()
.success(function(getData) {
$scope.comments = getData;
$scope.loading = false;
});
})
.error(function(data) {
console.log(data);
});
};
// function to handle deleting a comment
// DELETE A COMMENT ====================================================
$scope.deleteComment = function(id) {
$scope.loading = true;
// use the function we created in our service
Comment.destroy(id)
.success(function(data) {
// if successful, we'll need to refresh the comment list
Comment.get()
.success(function(getData) {
$scope.comments = getData;
$scope.loading = false;
});
});
};
});
<div class="comment-post>
<p ng-bind-html="comment.comment.content"></p>
</div>
Should do the trick.

Angular Background Slider using photos directly from foursquare

I'm working on adding some features to make my project app look better. It's an app that creates a chatroom in any building you are located nearby based on location. It is currently integrating foursquare to get the user's location, but also to get photos for the chatroom they entered (i.e. they enter a bar, it shows the first five photos that foursquare has on that bar). I want to make a background slider using angular, but I am beyond stuck on how to get it properly implemented.
Here is my code for the chatroom template:
<ng-include src="'/templates/navbar.html'"></ng-include>
<div ng-repeat="photo in photos" >
<img ng-src="{{photo.prefix}}300x300{{photo.suffix}}"></img>
</div>
<div class="container">
<div class="row " style="padding-top:40px;">
<h3 class="text-center">{{venue}} </h3>
<br />
<br />
<div class="col-md-8">
<div class="panel panel-info">
<div class="panel-heading">
RECENT CHAT HISTORY
</div>
<div scroll-glue class="panel-body" style="overflow-y: auto; height: 540px;">
<ul class="media-list">
<li class="media" ng-repeat="message in messages">
<div class="media-body">
<div class="media">
<a class="pull-left" href="#">
<img class="media-object img-circle" style="height: 57px; width: 88px; max-height: 57px; max-width: 88px;" ng-src="{{message.img}}" />
</a>
<div class="media-body">
<p class="chatText" ng-bind-html="message.message | emoji"></p>
<br />
<small class="text-muted">Posted by <b>{{message.username}}</b>, at {{message.createdAt}}</small>
<hr />
</div>
</div>
</div>
</li>
</ul>
</div>
<div class="panel-footer">
<form ng-submit="createMSG(message)">
<div class="input-group">
<input type="text" class="form-control" ng-model="message" placeholder="Enter Message" />
<span class="input-group-btn">
<span style="margin: 0 20px;" emoji-picker="message" placement="right" title="Emoji" recent-limit="12"></span>
<button class="btn btn-custom" type="submit">SEND</button>
</span>
</div>
</form>
</div>
</div>
</div>
<div class="col-md-4">
<div class="panel panel-primary">
<div class="panel-heading">
ONLINE USERS
</div>
<div class="panel-body">
<ul class="media-list">
<li class="media" ng-repeat="user in users">
<div class="media-body">
<div class="media">
<a class="pull-left" href="#">
<img class="media-object img-circle" style="height: 57px; width: 88px; max-height: 57px; max-width: 88px;" ng-src="{{user.img}}" />
</a>
<div class="media-body">
<h5>{{user.username}} | User </h5>
<small class="text-muted" style="color: green;"><b>Online</b></small>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
Here is my controller that allows you to check-in to the chatroom with the integrated foursquare:
angular.module('thesis.foursquare', ['ngRoute'])
.controller('CheckinController', ['$scope', '$location', '$window', '$cookies', '$rootScope', '$http', 'UserService',
function checkInCtrl($scope, $location, $window, $cookies, $rootScope, $http, UserService) {
if (!$cookies.get('id')) {
$location.path("/login");
} else {
// get users gps coords
navigator.geolocation.getCurrentPosition(function(position) {
$scope.lat = position.coords.latitude;
$scope.long = position.coords.longitude;
$http({
method: 'GET',
url: 'https://api.foursquare.com/v2/venues/explore/?client_id=AL4DDIM5HHXXYV1HKMQBGFLFIJRHJVPR4BI4CJ0VQIN4PHGZ&client_secret=VXRH3J0QWAJKGIPHMEIOWWR3YSADCO3S2IJQMS3BNVEDFYUE&v=20130815&ll=' + $scope.lat + ',' + $scope.long + '&radius=800'
}).then(function successCallback(response) {
$scope.venue = [];
$.map(response.data.response.groups[0].items, function(venues) {
$.map(venues, function(venue) {
if (venue.id) {
var aVenue = {};
aVenue.id = venue.id;
aVenue.name = venue.name;
aVenue.location = venue.location;
aVenue.contact = venue.contact;
$scope.venue.push(aVenue);
}
});
});
});
}, function error(msg) {
alert('Please enable your GPS position future.');
}, {
maximumAge: 600000,
timeout: 5000,
enableHighAccuracy: true
});
$scope.venue = [];
var checkin = function() {
};
// url: 'https://api.foursquare.com/v2/venues/explore/?client_id=AL4DDIM5HHXXYV1HKMQBGFLFIJRHJVPR4BI4CJ0VQIN4PHGZ&client_secret=VXRH3J0QWAJKGIPHMEIOWWR3YSADCO3S2IJQMS3BNVEDFYUE&v=20130815&ll=40.7,-74&query=' + search + '&near=' + currentLocation
// https://api.foursquare.com/v2/venues/explore/?client_id=AL4DDIM5HHXXYV1HKMQBGFLFIJRHJVPR4BI4CJ0VQIN4PHGZ&client_secret=VXRH3J0QWAJKGIPHMEIOWWR3YSADCO3S2IJQMS3BNVEDFYUE&v=20130815&ll=29.9407336,-90.0820647&radius=200
$scope.joinChat = function(id, name) {
if ($cookies.get('id')) {
$rootScope.venue = name;
$rootScope.id = id;
$http({
method: 'GET',
url: 'https://api.foursquare.com/v2/venues/' + id + '/photos?client_id=AL4DDIM5HHXXYV1HKMQBGFLFIJRHJVPR4BI4CJ0VQIN4PHGZ&client_secret=VXRH3J0QWAJKGIPHMEIOWWR3YSADCO3S2IJQMS3BNVEDFYUE&v=20130815&ll=40.7,-74&limit=5'
}).then(function successCallback(response) {
$rootScope.photos = response.data.response.photos.items;
});
UserService.joinchat(id).success(function(data) {
$location.path("/chatroom");
});
} else {
$location.path("/login");
}
};
}
}
]);
Here is the controller for the chatroom template:
angular.module('thesis.chatroom', ['luegg.directives', 'emoji', 'vkEmojiPicker', 'mgcrea.ngStrap'])
.controller('ChatroomController', ['$scope', '$location', '$window', '$cookies', '$rootScope', '$http', 'UserService', 'chatSocket',
function AdminUserCtrl($scope, $location, $window, $cookies, $rootScope, $http, UserService, chatSocket) {
if (!$cookies.get('id')) {
$location.path("/login");
} else {
$scope.users = [];
$scope.messages = [];
$scope.id = $rootScope.id;
var chatId = $scope.id;
$rootScope.id = null;
chatSocket.emit('joinedChat', {
chatId: $scope.id
});
chatSocket.on('message', function(data) {
console.log(data);
$scope.messages = data.messages;
$scope.users = data.users;
});
$scope.$on('$destroy', function() {
if ($scope.users.length === 1) {
chatSocket.emit('DestroyChat', {
idChatroom: chatId,
idUser: $cookies.get('id')
});
chatSocket.removeListener();
} else {
chatSocket.emit('leaveChat', {
idUser: $cookies.get('id')
});
chatSocket.removeListener();
}
});
$scope.createMSG = function(msg) {
if ($cookies.get('id')) {
UserService.createMSG(msg, chatId, $cookies.get('id')).then(function(data) {});
$scope.message = "";
} else {
$location.path("/login");
}
};
}
}
]);
current result:
All images show up, but cannot figure out the angular slider
Any suggestions/tips/criticisms are always appreciated. Thank you in advance!

Angular and Laravel - fetch data from mysql

I need to fetch data from my database, updated a div and onclick update another div.
I managed to fetch the data but I fail to load additional by onCLick.
My Code:
var app = angular.module('mainApp', [], function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
app.controller('mainController', function($scope, $http) {
$scope.fetcheddata = [];
$scope.loading = false;
$scope.init = function() {
$scope.loading = true;
$http.get('/api/content').
success(function(data, status, headers, config) {
$scope.fetcheddata = data;
$scope.loading = false;
});
}
$scope.getDesc = function() {
$scope.loading = true;
$http.get('/api/content/get/' + item.id).
success(function(data, status, headers, config) {
$scope.fetcheddata = data;
$scope.loading = false;
});
}
$scope.init();
});
View Code:
<div class="col-xs-2 type-image" tr ng-repeat='item in fetcheddata'>
<a href="#" class="thumbnail click-productgroup" data-group="show-<% item.group %>">
<img src="<% item.image %>" class="img-responsive">
</a>
</div>
The -tag should fetch the item.description and update another div. How can I do that?
I tried with an getDesc scope. Is this right? But how do I updated the div?
EDIT 1:
<div class="row">
<div class="col-md-7" id="productGroups">
<div class="row type-row">
<div class="col-xs-2 type-image" ng-repeat='item in fetchedData'>
<a href="#" class="thumbnail" ng-click='getDesc(<% item.id %>)'>
<img src="<% item.image %>" class="img-responsive">
</a>
</div>
</div>
</div>
<div class="col-md-5 type-description">
<% fetchedDesc | json %>
</div>
</div>
and in my controller:
$scope.getDesc = function() {
$scope.loading = true;
$http.get('/api/content/get/' + item.id).
success(function(data, status, headers, config) {
$scope.fetchedDesc = data.description;
$scope.loading = false;
});
}
Still the page jumps on click to the top and no content in the div (although ng-binding appears in the html).
Firstly, the page is jumping because the href of your anchor tag is #, remove that to stop it from happening :).
Secondly, I think the best way of achieving what you're after would be to ensure that each item fetched from the server in the $http.get('/api/content') call has the description as a property, rather than fetching it seperately, and then do something like this:
$http.get('/api/content').
success(function(data, status, headers, config) {
$scope.items = data;
});
$scope.selectItem = function(item) {
$scope.selectedItem = item;
}
And in the view:
<div class="col-xs-2 type-image" tr ng-repeat='item in items'>
<a href="" class="thumbnail click-productgroup" ng-click="selectItem(item)">
<img src="{{ item.image }}" class="img-responsive">
</a>
</div>
<div>
{{ selectedItem.description }}
</div>
I notice that is your getDesc you don't pass item.id?
$scope.getDesc = function(item) {
$http.get('/api/content/get/' + item.id)
.then(function(data) {
console.log(data)
})
}
This should come from ng-click of the div tag?
<div class="col-xs-2 type-image" tr ng-repeat='item in fetcheddata'>
<a href="#" class="thumbnail click-productgroup" data-group="show-<% item.group %>" ng-click="getDesc(item)">
<img src="<% item.image %>" class="img-responsive">
</a>
</div>

angularjs - Trouble getting data from database within template file

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);
};

Categories

Resources