I'm new to AngularJs. I'm having some trouble with this task.
I have the json file:
[{
"day": {"date": "12.01.2015", "dow": "monday", "in":"1"},
"lessons": [
{"time": "9.45 – 12.35", "title": "title", "teacher": "tname", "room": "3"},
... more lessons ...
]
},
... more days ...
]
My html file:
<table style="width: 100%;" class="table table-bordered">
<tbody ng-repeat="timetable in timetables" ng-if="ind==-1||ind==$index">
<tr ng-repeat="lesson in timetable.lessons">
<td rowspan="{{timetable.lessons.length}}" ng-if="!$index" style="vertical-align: top; text-align: left;">
{{timetable.day.date}}<br />
<div style="width: 100%; height: 100%; min-height: 100%; ">
<a href="#/list/{{timetable.day.in - 1}}" > {{timetable.day.dow}}</a></div>
</td>
<td>{{lesson.time}}</td>
<td>{{lesson.title}}</td>
<td>{{lesson.teacher}} <input type="textbox" ng-model="lesson.teacher"/></td>
<td>{{lesson.room}}</td>
</tr>
</tbody>
</table>
controllers.js:
angular.module('schedule.controllers', [])
.controller('ListLessonsCtrl', ['$scope', 'Schedule' , "$routeParams",
function ($scope, Schedule, $routeParams) {
if ($routeParams.ind === undefined) {
$scope.ind = -1;
} else {
$scope.ind = $routeParams.ind;
}
$scope.timetables = Schedule.query(); // get data form json file
$scope.save = function() {
Schedule.save($scope.timetables); // not works properly
};
}
])
... more code ...
And, finally, my services.js file:
angular.module('schedule.services', ['ngResource'])
.factory('Schedule', ['$resource', function($resource) {
return $resource('schedule/schedule.json', {}, {
query: {method: 'GET', isArray: true},
save: {method: 'POST'}
});
}]);
I need to get data from json file (done), update it on the page (know how to do it), and save updated data back to json file.
I tried to add function "save" to existing factory, but I don't know exactly, how to send data to it.
Could someone help me with it?
Thanks in advance!
Related
I have a problem exporting with pdfhtml5. I have data on datatable with HTML and CSS style and want to visualize it on pdf or another plugin.
this is the variable exportOptions
var thisExportOptions = {
exportOptions: {
rows: function(idx, data, node) {
var checkedB = sontCoches(".dt-class-checkbox", "entireRow");
var dt = new $.fn.dataTable.Api('#datatable-configuration');
$(checkedB).each(function(i, v) {
dt.row(this).select();
});
var selected = dt.rows({ selected: true }).indexes().toArray();
if (selected.length === 0 || $.inArray(idx, selected) !== -1)
return true;
return false;
},
columns: ':visible'
}
};
and this for datatable id
var table = $('#datatable-configuration').DataTable({
"ajax": {
"url": "/backend/index.php",
"dataType": "json",
"type": "GET",
"data": {
"app": get ["app"],
"module": get ["module"],
"element": cElement,
"action": "serverside",
"actionParent": get ["action"],
//"get": get,
}
},
"buttons": [
$.extend(true, {}, thisExportOptions, { text: 'Imprimer', extend: 'print' }),
$.extend(true, {}, thisExportOptions, { text: 'PDF', extend: 'pdfHtml5' }),
{ extend: 'colvis', text: 'Export colonnes', className: 'btn-primary', columns: ":not(.notConcernedByColvis)" }
],
"fnStateLoad": function(oSettings) {
return JSON.parse(localStorage.getItem('dataTableStore'));
},
"stateSaveParams": function(settings, data) {
data.columns.forEach(function(column) {
delete column.visible;
});
}
)}
Php code
$datas[$key]['nom'] = "<span class='font-weight-bold text-success'>" . $brute->raison_sociale . "</span>";
$datas[$key]['nom'] .= (!empty($brute->rcs_siret)) ? "<br /><small><span class='font-weight-bold'>RCS : </span><span class='right'>" . $brute->rcs_siret . "</span></small>" : "";
$datas[$key]['autres'] = '';
And the pdf file is like this
Pdf export with no css and HTML no interpreted
Finally I found WkHtmlToPdf it can convert HTML page to PDF file.
It's very helpfull and free, PHP WkHtmlToPdf provides a simple and clean interface to ease PDF and image creation when you want only use free solution on your project.
For more information : https://github.com/mikehaertl/phpwkhtmltopdf
I'm a newbie when it comes to Angular, but, I really want to improve myself and learn, butttt now I have a big big problem.
I don't know how to get the sum for every row I checked ..only for the value entity.
Here you have a plunker with my try code.
https://plnkr.co/edit/iBdEtQU1gPrCSxXQ2yyW?p=preview
Thanks alot !
View HTML:
<table style="border: 1px solid black">
<thead>
<tr>
<th></th>
<th>Id</th>
<th>Name</th>
<th>Address</th>
<th>Value</th>
</tr>
<td><b>Total</b></td>
</tr>
<tbody ng-repeat= "values in getSelected()">
<td></td>
<td>{{values.id}}</td>
<td>{{values.name}}</td>
<td>{{values.address}}</td>
<td>{{values.value}}</td>
</tbody>
</thead>
</table>
Controller code:
$scope.employees = [
{ id:"1", name: "A", address: "A1", value:10},
{ id:"2", name: "B", address: "A2",value:15 },
{ id:"3", name: "C", address: "A3",value:20},
{ id:"4", name: "D", address: "A4",value:25 },
{ id:"5", name: "E", address: "A5" ,value:30},
]
$scope.getSelected = function () {
var ar = $scope.employees.filter(function (value) {
if (value.checked == 1) {
return true;
} else {
return false;
}
});
console.log(ar);
return ar;
};
I'm assuming you want to get the sum of values of all selected rows. You may iterate over the array of selected items and sum up the values:
function() {
return $scope.getSelected().reduce((sum, item) => {
return sum + item.value;
}, 0);
}
Working example: https://plnkr.co/edit/TKDuKQB4rFO5U6w0bEBl?p=preview
Having problem with creating table from json data.
Using Django + AngularJS
Data is not displayed.
tables.js
app.controller('tableCtrl', function(ngTableParams, tableData) {
var data = tableData
this.tableLatestContests = new ngTableParams({
page: 1,
count: 5,
}, {
total: data.length,
getData: function($defer, params) {
$defer.resolve(data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
}
});
services.js
app.service('tableData', [$resource, function($resource) {
this.data = $resouce('data/table.json', {}, {
query: {
method: 'GET',
isArray: true,
}
}
});
data/table.json
[
{"id": 1, "market": "name", "uid": "uid"},
{"id": 2, "market": "name2", "uid": "uid2"},
]
table.html (on app changed {{ & }} to // & // because of django syntax)
<div class="card-body card-padding" data-ng-controller="tableCtrl as tctrl">
<table ng-table="tctrl.tableLastestContests" class="table table-striped table-vmiddle">
<tr ng-repeat="w in $data">
<td data-title="'ID'"> // w.id // </td>
<td data-title="'MARKET'"> // w.market // </td>
<td data-title="'UID'"> // w.uid // </td>
</tr>
</table>
</div>
Any ideas how to read and display table with tada from json ?
You are misunderstanding something. $resource creates instance of service instead of getting data from the service. This is why you have service which is capable of getting data form json instead of data form json.
this.srv = $resouce('data/table.json', {}, {
query: {
method: 'GET',
isArray: true,
}
}
this.data = this.srv.query();
After successful loading you will get data in this.data.
Of course you can change last line to something like this:
var _self = this;
this.srv.query(function(response) {
_self.data = response;
});
In case you do not want to create service, you can do:
$http.get('data/table.json').then(function(response) {
_self.data = response.data;
});
My post does not include support for errors.
You can read more here:
https://docs.angularjs.org/api/ngResource/service/$resource
https://docs.angularjs.org/api/ng/service/$http
Also, you have error in view. Use data instead of $data in ng-repeat.
I'm using backbone.
I have a json data like:
{"status": 7,
"organizations":[{"org_address":"\u4e2d\u56fd\u5317\u4eac\u5e02\u671d\u9633\u95e8\u59161001\u53f7", "job_positions": ["\u526f\u603b"], "org_id": 6, "org_name": "\u6570\u7ef4\u7f51\u7edc"}], "first_name": null, "last_name": null, "create_date": "2013-06-26 16:29:44.314000", "name": "\u66f9\u4f1f", "extra_emails": [null], "tags": [["friend"]], "nick_name": "\u4f11\u606f\u4e00\u4f1a\u513f", "gender": "\u7537", "image": null, "created_by": "system", "effective_start_date": "2013-06-26 16:29:44.314000", "social_medias": [{"url": "http://weibo.com/12345", "party_rel_id": 5, "type": "\u65b0\u6d6a\u5fae\u535a", "party_id": null, "sm_id": "\u6570\u636e\u5e93\u4e13\u5bb6"}], "date_of_birth": "1980-04-01", "extra_phones": {"office_phone": "82323333", "fax": "82324433"}, "mobile_phone": "17782272211", "primary_email": "weic#xy.com", "id": "5", "isUser": false}
my backbone model is:
var ContactDetail = Backbone.Model.extend({
urlRoot: URL_CONTACTS1+"3/5"
});
var ContactDetailCollection = Backbone.Collection.extend({
model: ContactDetail,
url: URL_CONTACTS1+"3/5"
})
my backbone view is:
var ContactDetailItemView = Backbone.View.extend({
tagName: 'div',
tagClass: 'border',
template: _.template($('#contactdetail-template').html()),
render: function() {
this.$el.html( this.template(this.model.toJSON()));
return this;
}
});
var ContactDetailListView = Backbone.View.extend({
el: $('#main'),
initialize: function(){
this.listenTo(this.collection, 'reset', this.render);
},
render: function() {
this.$el.empty();
this.collection.each( function( $model ) {
var itemview = new ContactDetailItemView({model: $model});
this.$el.append( itemview.render().el );
}, this);
return this;
},
})
the entrance is:
ContactDetailManagePageModel.prototype.init = function(){
var myContactDetails = new ContactDetailCollection();
contactDetailListView = new ContactDetailListView({
collection: myContactDetails
});
myContactDetails.fetch({reset:true});
}
In the html,I get data like this:
<tr>
<td><span class="Name_text"><%=name%></span> <%=primary_email%></td>
</tr>
<tr>
<td><%=mobile_phone%></td>
</tr>
<tr>
<td><%=org_address%></td>
</tr>
But I can't get the data named "org_address",which is in object "organizations" in the json data,it said that the "org_address" is not defined.
Hope for your help.Thanks!
When you pass in a data object to an underscore template, underscore will resolve the objects properties to it's free variables, if one of those properties is in turn an array or itself an object you can access it just as you would in regular JavaScript using dot or bracket notation.
So for example with your JSON, since organizations is an array and it's first element contains the property org_address you can simply do the following to get the org_address
<%=organizations[0].org_address%>
You are also able to execute JavaScript code in your template, so if for example organizations contained an array of multiple organizations you could loop through them and print them all out. For example
<% for (var i = 0, len = organizations.length; i < len; i++) { %>
<tr><td>organizations[i].org_address</td></tr>
<% } %>
Try <%= organizations[0].org_address%>
hi i am new completely new to AngularJS.
Trying to communicate with a JSON API. The API is beign called i am getting results bit the results are not getting filled into the view.
Here is the view:
<div >
<div data-ng-repeat="order in ordersResult.orders">
{{error}}
<fieldset class="fieldset">
<legend>
<b>{{order.klant.straat}} {{order.klant.huisnummer}} - {{order.klant.bedrijf}}</b>
</legend>
<table class="table table-bordered table-striped table-hover">
<th>Broodje</th><th>Aantal</th>
<tr data-ng-repeat="(tag,aantal) in order.broodjes" data-ng-click="check()">
<td>{{tag}}</td><td>{{aantal}}x</td>
</tr>
<tr data-ng-repeat="(tag,opmerkingen) in order.broodjesSpeciaal">
<td>{{tag}}</td><td><span ng-repeat="opmerking in opmerkingen">1x {{opmerking}}<br></span></td>
</tr>
</table>
</fieldset>
</div>
</div>
Here is the Controller:
app.controller('BezorgController', function ($scope, $resource) {
function getToday(){
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm}
//return mm+""+dd+""+yyyy;
return "22052013";
}
$scope.ordersRequest = $resource('http://www.movieapphd.com/bertus/api.1.0.0/order/bezorging/:day?key=:key',
{day: getToday(), key: API_KEY },
{get: {method: "JSONP"}}
);
$scope.ordersResult = $scope.ordersRequest.get();
if($scope.ordersResult.size == 0){
$scope.error = "Geen bezorgingen vandaag";
}
});
Here is the json that i get:
{
"orders":[
{
"klant":{
"bedrijf":"X",
"straat":"Haarlemmer",
"huisnummer":"8"
},
"broodjes":{
"0.0":0
},
"broodjesSpeciaal":{
"0.0":[
"nothing"
]
}
},
{
"klant":{
"bedrijf":"Anouk Beauty Gangbang",
"straat":"Haarlemmer",
"huisnummer":"220"
},
"broodjes":{
"0.0":0,
"1.1":2,
"1.2":1,
"2.3":1
},
"broodjesSpeciaal":{
"0.0":[
"nothing"
]
}
},
{
"klant":{
"bedrijf":"Hans Kazan GoochelTrucs",
"straat":"Haarlemmer",
"huisnummer":"222"
},
"broodjes":{
"0.0":0,
"1.1":2,
"1.2":2,
"2.3":1,
"3.1":1
},
"broodjesSpeciaal":{
"0.0":[
"nothing"
],
"2.3":[
"zonder stukjes",
"met extra stukjes"
]
}
}
]
}
What am i doing wrong here?
From the AngularJS docs, you can't use that syntax for arrays, and it appears sometimes broodjes and broodjesSpecial are arrays, and sometimes associative arrays. Also, in the one case where broodjes is an associative array there are no keys.
needed to change the method to get since the API is located on the same server.