what i need
i need to render data in symfony2 twig file.
some one has marked my question duplicate ,i need to render data using angular js not using symfony.
js code
function EntryCtrl ($scope, $http) {
$scope.rootEntry = [];
$http.get('https://api.github.com/users/mralexgray/repos').success(function(root) {
$scope.rootEntry = root;
console.log($scope.rootEntry);
});
}
output of variable $scope.rootEntry
data
{
id: 1,
name: "afeef",
price: "20",
description: "this is test page"
},
{
id: 2,
name: "afeef",
price: "20",
description: "this is test page"
}
html code
<body >
<div class="row" ng-controller="EntryCtrl">
<---updated code -->
# i have tried map model as well as
<table ng-model="rootEntry">
<div id="treeview" class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
<ul>
<li ng-repeat="root in rootEntry">{{root.name}}</li>
</ul>
</div>
</table>
</div>
Exception variable rootEntry is does not exists
controller code
public function checkAction()
{
$this->render('bundlename:twigfilename');
}
error rootentry doesnot exist
i need to show json data in twig file
solution
1. it can be done through symfony2 by rendering the json data through controller
like $this->render('bundlename:twigfilename',array('rootEntry,['jsonstring']);
but i need to make http request to send data in twig file
im new in angular js any suggestion is most welcome
general way for angular rendering
var mockDataForThisTest = "json=" + encodeURI(JSON.stringify([
{
id: 1,
firstName: "Peter",
lastName: "Jhons"},
{
id: 2,
firstName: "David",
lastName: "Bowie"}
]));
var app = angular.module('myApp', []);
function PeopleCtrl($scope, $http) {
$scope.people = [];
$scope.loadPeople = function() {
var httpRequest = $http({
method: 'POST',
url: '/echo/json/',
data: mockDataForThisTest
}).success(function(data, status) {
$scope.people = data;
});
};
}
html code
<div ng-app="myApp">
<div ng-controller="PeopleCtrl">
<p> Click <a ng-click="loadPeople()">here</a> to load data.</p>
<table>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr ng-repeat="person in people">
<td>{{person.id}}</td>
<td>{{person.firstName}}</td>
<td>{{person.lastName}}</td>
</tr>
</table>
</div>
</div>
but in this question how could i render data in twig through angular js.
You have to change angular's interpolation markup. In fact, twig is using the same interpolation markup as angular: "{{ }}" that's why you had that error: twig is expecting a variable defined in your symfony controller.
To do so, you have to configure your application module:
angular.module('myApp',[]).config(function($interpolateProvider){
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
}
Now, in your twig page use [[ ]] instead of {{ }}:
<div ng-app="myApp">
<div ng-controller="PeopleCtrl">
<p> Click <a ng-click="loadPeople()">here</a> to load data.</p>
<table>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr ng-repeat="person in people">
<td>[[person.id]]</td>
<td>[[person.firstName]]</td>
<td>[[person.lastName]]</td>
</tr>
</table>
</div>
I hope this will help you :)
P.S: for resolving $http promises use then instead of succes (it is deprecated)
https://docs.angularjs.org/api/ng/service/$http#deprecation-notice
For people with this problem in the future: you can use {% verbatim %}. It tells Twig to not process the code inside.
In the next code you have how to get Twig and Angular working together.
{{ max(1, 3, 2) }} <<< The render is done by Twig
{% verbatim %}
<div ng-app="">
<p>Name : <input type="text" ng-model="name"></p>
Hello {{name}} <<< The render is done by Angular
</div>
{% endverbatim %}
More info in https://ourcodeworld.com/articles/read/215/how-to-use-angular-js-and-twig-without-the-conflict-of-double-curly-braces
Related
I try to develop the " Load More " using Ajax & PHP & MVC Pattern
but i get a problem that the new row added can't get it with ajax (it can't know him)
My ajax code :
$(document).ready(function(){
$(document).on('click','#More',function(){
var id = $(".theID").last().val();
alert(id);
$.ajax({
url:'/more',
method: 'POST',
data:{id:id},
success:function(data){
//if(data != ''){
$('#rank').append(data);
/*}else{
$('#Load').remove();
}*/
}
});
});
});
My PHP code in controller
$datas = User::loadMore($_POST['id']);
echo View::getTemplate('User/data.html',['datas'=>$datas]);
My HTML code
<tbody id='rank'>
<tr>
<td>
1
</td>
<td>
<img alt='' src='img/test.jpg'/>
</td>
<button class='theID' value="{{rank.ID}}" style='display: none'></button>
</tr>
</tbody>
<button id='More' style=''>More</button>
data.html code
{% for key,data in datas %}
<tr>
<td>
{{key}}
</td>
<button class='theID' value="{{data.ID}}" style='display: none'></button>
</tr>
{% endfor %}
The ajax code work correctly but when I get the data the ID was always the first one.
What I've been trying to do is to show the contents of ng-repeat. The problem is that I can't use the double curly braces, {{ value }}.
In case you haven't tried this, let me explain that this expression, {{ value }}, is going to find a variable named $value if you use Laravel 5.2. Apparently, using double curly braces, {{ value }}, won't refer to the content of ng-repeat, even if there is an expression like the following one.
<tr ng-repeat="value in values"></tr>
So, I usually rely on ng-bind, but ng-bind doesn't seem to work with ng-repeat as it usually does.
My code looks like this.
<div ng-app="angularApp" ng-controller="TableController as tc">
<input type="text" ng-model="searchBox">
<table style="width:100%;">
<tr>
<th>Student ID</th>
<th>Name</th>
</tr>
<tr ng-repeat="student in students | filter:searchBox">
{{ student.name }}//This causes an error, indicating "Use of undefined constant student"
<td ng-bind="student.student_id"></td>
<td ng-bind="student.name"></td>
</tr>
</table>
</div>
<script type="text/javascript">
angular.module('angularApp')
.controller('TableController', function(){
this.data = {
students: [
#foreach($students as $student)
"{{ $student }}",
#endforeach
]
};
});
</script>
$students is an array, containing SQL objects called student. This comes from a Laravel's controller function.
Do you see anything I'm doing wrong? Any advice will be appreciated!
In your script:
<script type="text/javascript">
angular.module('angularApp', [], function($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
});
angular.controller('TableController', function(){
this.data = {
students: $students
};
});
In your blade:
Change {{ student.name }} to [[ student.name ]]
You can add an # before it
https://laravel.com/docs/5.2/blade#displaying-data
Since many JavaScript frameworks also use "curly" braces to indicate a
given expression should be displayed in the browser, you may use the #
symbol to inform the Blade rendering engine an expression should
remain untouched. For example:
Laravel
Hello, #{{ name }}.
this is what it shows on clicking tab one time 2nd time I click it loads last two file .15 and .17 again alltogetherthis is shown in console when I inspect even if I have not clicked on tab.And displays this data in browser when I click tab. This should not be shown whn console is clicked while inspectin page. Data only to be loaded only when I click tab.
Object {type: "FeatureCollection", metadata: Object, features:Array[11], bbox: Array[6]}bbox: Array[6]features: Array[11]metadata: Objecttype: "FeatureCollection"proto: Object
here is my code..
<body ng-controller="CountryCtrl">
<div ng-app ng-init="tab=1">
<div class="cb" ng-click="tab = 1">tab 1</div>
<div class="cb" ng-click="tab = 2">tab 2</div>
<div ng-show="tab == 1">
<p>hellloollllllllllllo</p>
</div>
<div ng-show="tab == 2">
<h2>Angular.js JSON Fetching Example</h2>
<table border=1>
<tr>
<th>type</th>
<th>properties_mag</th>
<th>properties_place</th>
<th>properties_time</th>
<th>properties_upated</th>
<th>properties_tz</th>
</tr>
<tr ng-repeat="type in country ">
<td>{{type.type}}</td>
<td>{{type.properties.mag}} </td>
<td> {{type.properties.place}} </td>
<td> {{type.properties.time}} </td>
<td> {{type.properties.updated}} </td>
<td> {{type.properties.tz}} </td>
<tr ng-repeat="cor in features.geometry.coordinates ">
<td> {{cor}} </td>
</tr>
</table>
</div>
this is controller function.....
var countryApp = angular.module('countryApp',[]);
countryApp.controller('CountryCtrl', function ($scope, $http){
$http.get('http:/4.5_day.geojson').success(function(data) {
console.log(data);
$scope.country = data.features;
$scope.coor=data.features.geometry.coordinates;
console.log($scope.country);
});
});
I would suggest that you simply call the function that loads the JSON data when clicking the second tab using ng-click. This way you will not get it loaded unless the tab is clicked.
You could change:
<div class="cb" ng-click="tab = 2">tab 2</div>
To:
<div class="cb" ng-click="switchTabAndLoadData()">tab 2</div>
And defined the function in your controller to update the tab variable and load the JSON.
You are calling the $http service directly in your controller that's why the data is loaded up front. Try this:
var countryApp = angular.module('countryApp',[]);
countryApp.controller('CountryCtrl', function ($scope, $http){
var loadData = function(){
$http.get('http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_day.geojson').success(function(data) {
console.log(data);
$scope.country = data.features;
$scope.coor=data.features.geometry.coordinates;
console.log($scope.country);
});
}
$scope.switchTabAndLoadData = function(){
$scope.tab=2;
if(angular.isUndefined($scope.country) || angular.isUndefined($scope.coor)){
loadData();
}
}
});
Make sure to also apply the HTML change I previously suggested and it should be fine.
You problem lies elsewhere, had you checked the console you would have seen that angular gives an error on your assignment of variables for $scope.coor since you are trying to assign properies of an object in an array of object.
Check this pen for a solution: http://codepen.io/anon/pen/BjXGGJ
You can then adjust the HTML do your needs.
I'm new in Symfony2 and AngularJS. I´m trying to use json_encode to show my database's content. But it doens't work. This is my controller:
public function catalogonewAction()
{
$data = $this->getDoctrine()->getManager()
->getRepository('AcmeRetroBundle:Game')->findAll();
return $this->render('AcmeRetroBundle:Default:catalogonew.html.twig',
array('data' => json_encode($data)));}
This is my html.twig:
{% verbatim %}
<div ng-app="myApp1" ng-init="mydata = {{ list|raw }}">
<table id="sortedData">
<tr><th>T1</th><th>T2</th></tr>
<tr ng-repeat="data in mydata | filter:sortData">
<td>{{data.nombreJuego}}</td>
<td>{{data.description}}</td>
</tr>
</table>
</div>
{% endverbatim %}
And my app.js:
angular.module('myApp1', []).
filter('sortData', function() {
alert('Hi');
return out;
});
When I refresh my page it is shown this:
T1 T2
{{data.nombreJuego}} {{data.description}}
What is wrong?
I don't like to pass data from back-end to an
anuglarJS like that, it's a common to use ajax request to retrieve data.
Try to pass you data to a javascript variable that you could affect is to an object in you angular scope :
<script>
var list= {{ data }}
</script>
{% verbatim %}
<div ng-app="myApp1" ng-init="mydata = list">
<table id="sortedData">
<tr><th>T1</th><th>T2</th></tr>
<tr ng-repeat="data in mydata | filter:sortData">
<td>{{data.nombreJuego}}</td>
<td>{{data.description}}</td>
</tr>
</table>
</div>
{% endverbatim %}
So i create a search engine in my laravel application, the only problem i have is displaying it on the same page,
this is what i have in my views
<div class="search">
{{Form::open(array('url' => 'admin/search', 'method' => 'post'))}}
{{Form::text('keyword',null,array(
'class' => 'form-control',
'placeholder' => 'Enter keyword...'
))}}<br>
{{Form::submit()}}
</div>
<br>
<div class="searchs">
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<th>Title</th>
<th>Date Created</th>
<th>Actions</th>
</thead>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
</div>
and in my controller
public function search_keyword()
{
$input = Input::get('keyword');
$result = Post::where('title','LIKE','%' .$input. '%')->get();
return Redirect::route('index')
->with('result',$result);
}
but i was hoping that i could do this in ajax request but I don't know jquery or even js.. help
You have to catch the submit of the form with Javascript (vanilla or e.g. jquery), find the value the user is searching for and start an ajax request. (jQuery $.get() or native XMLHttpRequest())
Now you need to make sure that laravel accepts the ajax request properly and return the request as JSON.
If your request successfully returns data, use the success function of the ajax request to process the data. During the search, you could show some loading icon to notify the user that the search process is running.
To start with, add an id to the form and use jquery to listen for the submit event.
<script type="text/javascript">
$('#my-form').on('submit', function(event) {
event.preventDefault();
$.ajax({
url: "/api/search",
type: 'POST',
data: {
value: $("input:first").val()
},
dataType: 'json',
success: function (response) {
console.log(response);
}
});
});
</script>
Next, register a route for the /api/search request and return your search request with return response()->json(['result' => $result]); (laravel 5)
If everything is right, you should see the result in the console of your browser.