Angular and Laravel - fetch data from mysql - javascript

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>

Related

ng-src not resolving image path stored in MongoDB

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.

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.

ng-show Displaying all items

Continue working with angularjs and now having problem with ng-show which on click it show me all hidden data. As I understand, I need to specify ID of clicked item which I want to show, from my example i'm using ng-model which had boolean value and on click it change on true, that's why it's showing all items. Tell me please, how can I show item which I had selected?
<div class="list-group" ng-click="SetItemVisible()" ng-repeat="q in feed">
<a href="" class="list-group-item">
<h4 ng-model="showItem" class="list-group-item-heading">{{q.title}}</h4>
<p ng-show="showItem" value="true" class="list-group-item-text">{{q.body}}</p>
</a>
</div>
And js:
$scope.SetItemVisible = function () {
if (!$scope.showItem) {
$scope.showItem = true;
} else {
$scope.showItem = false;
}
}
$scope.feed = [];
function getRssItems() {
rssFeedService.getFeed().then(function (results) {
$scope.feed = results.data;
}, function (error) {
//alert(error.data.message);
});
}
You can do dis by:
$scope.feed = [{
'title': "A",
'body': "testA body"
},
{
'title': "b",
'body': "testb body"
}
]
$scope.showItem = {};
$scope.SetItemVisible = function (index) {
$scope.showItem[ index] = true;
}
<div class="list-group" ng-click="SetItemVisible($index)" ng-repeat="q in feed track by $index">
<a href="" class="list-group-item">
<h4 ng-model="showItem[$index]" class="list-group-item-heading">{{q.title}}</h4>
<p ng-show="showItem[$index]" value="true" class="list-group-item-text">{{q.body}}</p>
</a>
For live demo click here: http://plnkr.co/edit/ApI9eb8eQlBdoMUkn8do?p=preview
<div class="list-group" ng-click="q.showItem != q.showItem" ng-repeat="q in feed">
<a href="" class="list-group-item">
<h4 ng-model="showItem" class="list-group-item-heading">{{q.title}}</h4>
<p ng-show="q.showItem" value="true" class="list-group-item-text">{{q.body}}</p>
</a>
</div>
Assuming following JSON for feed
[
{
"title":"test1",
"body":"test body 1",
"show":false
},
{
"title":"test2",
"body":"test body 2",
"show":false
}
]
HTML
<body ng-controller="MainCtrl">
<div class="list-group" ng-repeat="q in feed">
<a class="list-group-item">
<h4 ng-click="q.show=!q.show" class="list-group-item-heading">{{q.title}}</h4>
<p ng-show="q.show" value="true" class="list-group-item-text">{{q.body}}</p>
</a>
</div>
JS
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $http) {
$scope.feed = [];
$http.get('feed.json').then(function (results) {
$scope.feed = results.data;
}, function (error) {
//alert(error.data.message);
});
});
Check out here

Can i retain old value of scope and update some other value to other div in AngualrJS

Well,I'll try to explain my approach why I am doing this. I have trimmed the code for the sake of simplicity. I want to create one div where there should be <h4>BroadCategory Name</h4> and below this headline, I am calling one API to fetch some images associated with that BroadCategory Name
<div ng-controller="NavigationController">
<div ng-repeat="primaryItems in categories">
<div>
<h4><span>{{primaryItems.BroadCategory}}</span></h4>
</div>
<div ng-init="getImgForCategory(this.primaryItems)">
<div ng-repeat="ad in ads">
{{ ad.ad_type }}
<a ng-href="#productList/{{primaryItems.BroadCategory}}">
<img src="{{ ad.images[0] }}" >
</a>
</div>
</div>
</div>
</div>
My Controller:
$http.get("/get_categories/")
.success(function(response){
$scope.categories = response;
})
.error(function (msg) {
console.log(msg);
});
$scope.getImgForCategory = function (categoryInfo) {
var category = (categoryInfo.BroadCategory);
$http.get('/Some_API_ad_type='+category) //API to fetch some images associated with that **BroadCategory**
.success(function (response) {
$scope.ads = response;
})
.error(function (msg) {
console.log(msg);
})
}
Issue : Issue is that $scope.ads keeps the value of last called API response and so the {{ ad.ad_type }} and similar ads attributes have all the same values (which is the response for the last BroadCategory name)
How can I resolve this with best Angular approach?
<h1>Expected Output: </h1>
<h4>BroadCategory1</h4>
BC1_data1
<br>BC1_data2
<h4>BroadCategory2</h4>
BC2_data1
<br>BC2_data2
<h1>Actual Output: </h1>
<h4>BroadCategory1</h4>
BC2_data1
<br>BC2_data2
<h4>BroadCategory1</h4>
BC2_data1
<br>BC2_data2
Well, the generated html in your inner ng-repeat all use the same $scope.ads list. So if that gets updated, all data on your screen will just show the new value of $scope.ads.
What I would do is link the adds to the category. Like the following:
$scope.getImgForCategory = function (categoryInfo) {
var category = (categoryInfo.BroadCategory);
$http.get('/Some_API_ad_type='+category)
.success(function (response) {
categoryInfo.ads = response;
})
.error(function (msg) {
console.log(msg);
})
}
.
<div ng-controller="NavigationController">
<div ng-repeat="primaryItems in categories">
<div>
<h4><span>{{primaryItems.BroadCategory}}</span></h4>
</div>
<div ng-init="getImgForCategory(primaryItems)">
<div ng-repeat="ad in primaryItems.ads">
{{ ad.ad_type }}
<a ng-href="#productList/{{primaryItems.BroadCategory}}">
<img src="{{ ad.images[0] }}" >
</a>
</div>
</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