Angular ng-repeat not showing data on laravel? - php

The console shows that the posts were retrieved successfully, the backend works fine without the angular compatibility.
and its supposed to retrieve post data.
angular.js:12701 XHR finished loading: GET
"http://127.0.0.1:8000/auth/posts".
however it shows 5 empty divs like the following
main.js
$http.get('/auth/posts').then(function(data){
$scope.myposts = data;
});
PostController
public function getPosts()
{
$posts = Post::all();
return json_encode($posts);
}
Route
Route::get('auth/posts', 'HomeController#getPosts');
the html file
<div id="mypost" class="col-md-8 panel-default" ng-repeat="post in myposts">
<div id="eli-style-heading" class="panel-heading"><% post.title %></div>
<div class="panel-body panel">
<figure>
<p> <% post.body %></p>
</figure>
</div>
</div>

You need to access the data property from the response, I think you need,
$http.get('/auth/posts').then(function(data){
$scope.myposts = data.data;
});

Related

How to Pass Data From One View to Another in Laravel?

I am quite new to Laravel
I have two views
Book
Read
The Book View displays a single book
<section class="cont-readingone">
<div class="container">
<div class="row row-grid">
<div class="col-md-6">
<div class="row">
<div class="col-md-6">
<div class="cont-reading-image">
<img src="{{ $book->image_url }}" alt="trending image" />
</div>
</div>
<div class="col-md-6">
<div class="out-box">
<h2>{{ $book->name }}</h2>
<h3>{{ $book->author->name }}</h3>
<br>
Start Reading<br><br>
<img src="\images\cart-buy.png" width="13px"/> Buy
</div>
</div>
</div>
</div>
In my controller, I was able to achieve it using
public function show(Book $book) {
$relatedBooks = Book::where('author_id', $book->author_id)
->where('id', '!=', $book->id)
->get();
return view('book')->with('book', $book)->with('relatedBooks', $relatedBooks);
}
In my web.php
Route::get('/books/{book}', [BooksController::class, 'show'])->name('book');
What I am trying to achieve is that, when I click Start Reading on
the Single Book Page, it takes me to another view page (Read) but it takes the book id that I clicked.
In the Read View I have this code,
<script>
"use strict";
document.onreadystatechange = function () {
if (document.readyState == "complete") {
window.reader = ePubReader("{{ $book->epub_url }}", {
restore: true
});
}
};
</script>
My problem is that I don't know how to take the id of the book that I
click and Pass it to the Read View
I will be glad if someone can explain the logic to me as I am confused.
To do via POST
//Book View
//change Start Reading to
<form action="{{ route("your.route.to.read") }}" method="POST">
#csrf
<input name="book_id " value ={{$book->id}} hidden>
<button type="submit">Start Reading</button>
</form>
//your Route will be
Route::get('/read',YourReadController#yourFunction)->name('your.route.to.read');
//your controller will be
public function yourFunction(Request $request)
{
//book id is in $$request->book_id
//your operation here
return view('read')->with('data',$dataYouWantToSend);
}
To do via GET
//Book View
//change Start Reading<br><br> to
Start Reading
//route for get will be
Route::get('/read/{book_id}',YourReadController#yourFunction)->name('your.route.to.read');
//your countroller will be
public function yourFunction($book_id)
{
//book id is in $book_id
//your operation here
return view('read')->with('data',$dataYouWantToSend);
}

AngularJS ng-repeat for one row in PDO fetch

I am newer to Angular and seem to be having difficulty finding out why I'm getting blank fields. I'm using the 1.7.7 version of angular-min and angular-route.
The data is being pulled from a table called "news" and I am only needing the ID and ARTICLE columns. The ARTICLE column is stored from a CKEditor textarea.
My route looks like:
var app = angular.module("HabbfinityApp", ["ngRoute"]);
app.config(['$routeProvider','$locationProvider',
function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when("/", {
templateUrl : "home.php"
}).when("/home", {
redirectTo : "/"
}).when("/news", {
templateUrl : "news.php"
}).when("/newsinfo/:id", {
templateUrl : "newsinfo.php",
controller: "newsList"
}).otherwise({
redirectTo : "/"
});
}]);
app.controller("newsList", function($scope, $http, $routeParams){
var id = $routeParams.id;
$http.get("newsitem.php?id=" + id)
.then(function(resp){
$scope.item = resp;
});
});
app.filter('unsafe', function($sce) {
return function(val) {
return $sce.trustAsHtml(val);
};
});
My newsitem.php looks like:
<?php
require('config2.php');
$id = $_GET["id"];
$newsQuery = $dbh->prepare("SELECT id, article FROM news WHERE id=:id LIMIT 1");
$newsQuery->execute(array(":id"=>$id));
$newsQueryData = $newsQuery->fetch(PDO::FETCH_ASSOC);
echo json_encode($newsQueryData);
?>
My newsinfo.php looks like:
<div class="row">
<div class="col-md-12">
<div class="panel-default panel-custom">
<div class="panel-heading">
<h3 class="panel-title"><i class="fa fa-lg fa-newspaper-o" aria-hidden="true"></i> News</h3>
</div>
<div class="panel-body">
<div ng-controller="newsList">
<div ng-repeat="x in item">
<img src="assets/images/news.png" alt="News" class="img-center img-responsive">
<br>
Tweet
<br>
<br>
<p ng-bind-html="x.article | unsafe"></p>
</div>
</div>
</div>
</div>
</div>
</div>
ISSUE
After the first image, twitter button and actual article, everything gets repeated another five times, so I end up with six images and six tweet buttons where the ID of the repeated five is blank.
Here's a var_dump using htmlentities so you can see exactly what those columns are pulling in.
string(899) "{"id":"610","article":"<p style=\"text-align:center\"><strong><span style=\"font-size:26px\">All of us at habbfinity would like wish our<\/span><\/strong><\/p>\r\n\r\n<p style=\"text-align:center\"><strong><span style=\"font-size:26px\">Builder<\/span><\/strong><\/p>\r\n\r\n<p style=\"text-align:center\"><strong><span style=\"color:#2980b9\"><span style=\"font-size:48px\">Sarah<\/span><\/span><\/strong><\/p>\r\n\r\n<p style=\"text-align:center\"><img alt=\"Image result for happy birthday gif\" src=\"http:\/\/bestanimations.com\/Holidays\/Birthday\/flowers\/happy-birthday-vintage-roses-gold-gif.gif\" \/><\/p>\r\n"}"
I've tried doing:
<div ng-repeat="x in item | limitTo: 1">
That doesn't work.
TEMP FIX
After reading through some of the posts on here, I managed a temporary fix.
I added the following to the newsList controller:
$scope.id = $routeParams.id;
I then changed newsinfo.php by moving the image and twitter button outside of ng-repeat and changed {{x.id}} in the twitter link to {{id}}.
QUESTION
How can I fix this to allow everything to be within the ng-repeat without having to use the temporary fix?
Or is what was done for the temporary fix the better way of doing it anyway?
EDITED ANSWER / QUESTION
Thanks to the suggestion below, I was able to get this resolved.
However, I have one more question.
Is there a way to do this on one page? For example, news.php is just a list of news posts and newsinfo.php is the single news post. Am I able to do something to get it all on news.php and keep the route to only /news, which would show the list if the route isn't news/# or show the specific item if the route is news/#?

Laravel compact is not working

I'm trying to make a posting system, with a resource routing combination on the posts. When I try to run the app to view the posts, it returns an error stating that the posts could not be found within the view. I have the controller code for the index and the show functions:
public function index()
{
$posts = Post::latest()->get();
return view('view', compact('posts'));
}
public function show(Post $post)
{
return view('posts.show', compact('post'));
}
The view that I have for the app uses the post variable to display the posts:
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-2">
<div class="panel panel-default">
<!-- Posts will be displayed on the same panel -->
<div class="panel-body" id="view">
#foreach($posts as $post)
<article id="post">
<a href="/view/posts{{ $post->id }}">
{{ $post->title }}
</a>
<div class="body">
{{ $post->body }}
</div>
<!-- Footer for posts will include interaction features -->
</article>
#endforeach
</div>
</div>
</div>
</div>
</div>
Is there something that the laravel installation isn't doing correctly? Is the compact function set up correctly?
Your controller index function should be something like this:
public function index()
{
$posts = Post::get();
return view('posts.index', compact('posts'));
}
The return of the index action is wrong
return view('view', compact('posts'));
Change 'view' with 'posts'
Use compact('posts')
If you're a beginner checkout the laracasts video series to get a good understanding of the Laravel framework.

Multiple Jplayer audio players from Laravel DB

I'm trying to create multiple instances of Jplayers that each play a different audio file from my Laravel Database (table called archives) and i'm stuck at the point the jQuery code meets the Laravel code.
So far the audio players play but they play the same file.
also i have trouble when i navigate deeper into the website. ex: with mydomain.com/segments/ the audio player adds "segments" to the url instead of just the public directory. I know a similar issue can be solved with the URL:asset in Laravel, but i'm not sure how to with this since it's the jquery that's getting the file.
This is where i try to create my multiple jplayer instances using a laravel Forloop (i need to start at 2 because player 1 is being used elsewhere)I'm confused about how to mix the Laravel and Jquery code.
This is all in my footer.blade.php
<!--{{{$counter = 2}}}-->
#foreach ($archives as $archive)
<script>
var counter = "{{$counter}}";
var file = "archiveAudio/{{$archive->audioFile}}";
$(document).ready(function(){
$("#jquery_jplayer_"+ counter).jPlayer({
ready: function () {
$(this).jPlayer("setMedia", {
title: "Hidden",
mp3: file,
oga: ""
});
},
play: function() { // To avoid multiple jPlayers playing together.
$(this).jPlayer("pauseOthers");
},
swfPath: "../../js",
supplied: "mp3, oga",
cssSelectorAncestor: "#jp_container_" + counter,
wmode: "window",
globalVolume: true,
useStateClassSkin: true,
autoBlur: false,
smoothPlayBar: true,
keyEnabled: true
});
counter ++;
});
</script>
#endforeach
Home page Blade View (needs to start with #2 player add 1 to the player ID for each player it creates)
<div id="latest">
<!-- {{ $count = 2}} -->
#foreach ($archives as $archive)
<div class="singleLatest">
<img src = "/images/segments/{{$archive->segment->image}}" width="100px;"/>
<div class="playerAndInfo">
<h3> {{ $archive->archiveTitle}}<br>{{$archive->segment->name}}</h3>
<div id="jquery_jplayer_{{$count}}" class="jp-jplayer"></div>
<div id="jp_container_{{$count}}" class="jp-audio" role="application" aria-label="media player">
<div class="jp-type-single">
<div class="jp-gui jp-interface">
<div class="jp-controls">
<button class="jp-play" role="button" tabindex="0">play</button>
</div>
<div class="jp-progress">
<div class="jp-seek-bar">
<div class="jp-play-bar"></div>
</div>
</div>
<div class="jp-time-holder">
<div class="jp-current-time" role="timer" aria-label="time"> </div>
<div class="jp-duration" role="timer" aria-label="duration"> </div>
</div>
<div class="jp-no-solution">
<span>Update Required</span>
To play the media you will need to either update your browser to a recent version or update your Flash plugin.
</div>
</div>
</div>
</div>
</div><!--end playerAndInfo-->
</div> <!-- end single latest -->
<!-- {{ $count = $count +1}} -->
#endforeach
</div><!-- End latest -->
Thanks!

How to foreach angularjs php array json output

I'm new to AngularJs and i'm trying to make web with angular.js and PHP.I'm having some trouble on displaying data from a Json .
My controller
$scope.careprovider = function() {
$http.post('php/homefunctions.php', {
'act': 'careprovider'
}).success(function(data, status, headers, config) {
if (data.sessionError == 1) {
$location.path("/Login");
}else {
alert(data.careproviders);
$scope.careprovider = data.careproviders;
$scope.specializations = data.specializations;
}
}).error(function(data, status) {
$scope.errors.push(status);
});
}
I have JSON Array object as shown below
{"careproviders":
{"Anaesthesiologists":
[{"id":"37","addedBy":"5463e2dc0f","doctorName":"test","email":"sukalavan#consult-ic.com","hasUpdation":"NO"},
{"id":"38","addedBy":"62f5d33584","doctorName":"test1","email":"sukalavan#consult-ic.com","hasUpdation":"NO"}],
"Cardiologist":
{"id":"38","addedBy":"62f5d33584","doctorName":"test2","email":"sukalavan#consult-ic.com","hasUpdation":"NO"}]}
I want to get the keys and values separately using ng-repeat in angular.js.Here is my html
<div ng-repeat="f in careprovider">
<div class="cus-row-head">want show here the key</div>
<div class="row cus_row clearfix cus-sep-row posrel">
<div class="col-xs-12 col-md-12">
<div class="col-xs-6 col-lg-8 cus-col-mob-4">
<span class="cus-md-font">want to show here the doctor name</span>
<span class="cus-sm-font cus-inline">
<span class="glyphicon glyphicon-envelope"></span> email </span>
</div>
</div>
<a class="icons_sm icons-sm-edit"></a>
</div>
</div>
try this
{{f.doctorName}}
instead of "doctorName"
Check my plunker
Check out this jsfiddle I put together which has the type of structure you want.
If you want to loop through the keys of an object, your ng-repat should look like this:
<div ng-repeat="key in keys(object)"></div>
Where keys is defined in your controller as:
$scope.keys = function(obj){return obj? Object.keys(obj) : [];}
(BTW, your json has a missing '[' character in it.)
Try doing this:
ng-repeat="(key, value) in data"
Then you can access {{key}} and {{value}}
The method is mentioned here: https://docs.angularjs.org/api/ng/directive/ngRepeat

Categories