I have this simple XML View:
<core:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m"
controllerName="listicons.list" xmlns:html="http://www.w3.org/1999/xhtml">
<Page title="Title">
<content>
<List id="test-list"></List>
</content>
</Page>
</core:View>
In my controller, I call a method to build list items onInit. First of all set some data:
var data = {
"products": [
{
"prodName": "Apple",
"prodCountry": "Netherlands",
"price": "normal"
},
{
"prodName": "Orange",
"prodCountry": "Spain",
"price": "extra"
},
{
"prodName": "Strawberry",
"prodCountry": "Poland",
"price": "normal"
}
]
};
// create a Model with this data and attach it to the view
var model = new sap.ui.model.json.JSONModel();
model.setData(data);
this.getView().setModel(model);
var list = this.getView().byId("test-list");
Then I build the list and bind the items to it:
// bind the List items to the data collection
list.bindItems({
path : "/products",
sorter : new sap.ui.model.Sorter("prodName"),
//template : listTmpl
template : new sap.m.StandardListItem({
title: "{prodName}",
description: "{prodCountry}"
})
});
After I built the list and is alread rendered, I look after which items have an extra price and set an icon for them:
jQuery.each(list.getItems(), function(i, obj) {
if(obj.mProperties.price == "extra") {
obj.setIcon("sap-icon://flag");
}
});
So. Everything works fine. But I am not happy with my solution, because I'd rather like to manipulate the data BEFORE rendering the list. I tried to build a list template directly before binding the items to the list and then use this template like:
var listTmpl = jQuery.each(data.products, function(i, a) {
var lI = new sap.m.StandardListItem({
title: "{prodName}",
description: "{prodCountry}"
});
if(a.price == "extra") {
lI.setIcon("sap-icon://flag");
}
return lI;
});
But then my list is not shown and I got an error in the console, saying
Missing template or factory function for aggregation items of Element sap.m.List ...
Does anyone have an idea how to improve my sol.?
THX a lot..
IMHO, I think you can have the controller as clean as possible, and define most of the needed functionality (binding, template, sorter, and icon) in the XMLView:
<List id="test-list" items="{
path : '/products',
sorter : [{
path : 'prodName',
descending : true
}]
}">
<StandardListItem title="{prodName}"
description="{prodCountry}"
icon="{path:'price', formatter:'.getIconFlag'}" />
</List>
You then can rid of all the template binding and manipulation stuff you have in your controller, and you only need to specify the formatter function getIconFlag:
getIconFlag : function (sPrice) {
return sPrice === "extra" ? "sap-icon://flag" : null;
}
See the following working example:
sap.ui.controller("view1.initial", {
onInit : function(oEvent) {
var oModel = new sap.ui.model.json.JSONModel();
oModel.setData({
"products": [
{
"prodName": "Apple",
"prodCountry": "Netherlands",
"price": "normal"
},
{
"prodName": "Orange",
"prodCountry": "Spain",
"price": "extra"
},
{
"prodName": "Strawberry",
"prodCountry": "Poland",
"price": "normal"
}
]
});
this.getView().setModel(oModel);
},
getIconFlag : function (sPrice) {
return sPrice === "extra" ? "sap-icon://flag" : null;
}
});
sap.ui.xmlview("main", {
viewContent: jQuery("#view1").html()
})
.placeAt("uiArea");
<script id="sap-ui-bootstrap"
src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js"
data-sap-ui-theme="sap_bluecrystal"
data-sap-ui-xx-bindingSyntax="complex"
data-sap-ui-libs="sap.m"></script>
<div id="uiArea"></div>
<script id="view1" type="ui5/xmlview">
<mvc:View
controllerName="view1.initial"
xmlns="sap.m"
xmlns:core="sap.ui.core"
xmlns:mvc="sap.ui.core.mvc" >
<List id="test-list" items="{
path: '/products',
sorter: [{
path: 'prodName',
descending: true
}]
}">
<StandardListItem title="{prodName}" description="{prodCountry}" icon="{path:'price', formatter:'.getIconFlag'}" />
</List>
</mvc:View>
</script>
bind the value for price to a formatter-function. so you can create the icons dynamically from the value
list.bindItems({
path : "/products",
sorter : new sap.ui.model.Sorter("prodName"),
template : new sap.m.StandardListItem({
title: "{prodName}",
description: "{prodCountry}",
/* bind items to factory-function */
icon: {
path: "price",
formatter: function(price) {
if (price == "extra") {
return "sap-icon://flag";
}
}
}
})
});
ps: i did not test this, but it should work like this. if you receive errors just comment.
Related
I have imported the following json file:
[
{
"case_id": "1234",
"thread": [
{
"t_id": "1111",
"text": "test"
},
{
"t_id": "2222",
"text": "test"
}
]
},
{
"case_id": "5678",
"thread": [
{
"t_id": "9999",
"text": "test"
},
{
"t_id": "8888",
"text": "test"
},
{
"t_id": "777",
"text": "test"
}
]
}
]
using the following:
import cases from '../cases.json'
The whole json dataset is available in cases variable and can be used in the template with the support of v-if and v-for.
How can I create a separate dataset (thecase) that contains only threads for a given case_id? In the template I would only like to use v-for to display all threads for a given case_id.
Below is my export default section:
export default {
name: "details",
props: {
case_id: {
required: true,
type: String
}
},
data () {
return {
cases,
thecase: ### THIS IS THE PART I CANNOT FIGURE OUT ###
}
}
};
You can remove thecase from data options and use a computed property instead for thecase. Inside the computed property, we will need to use array .find() method to find the case where case_id is same as the case_id passed in the prop:
data: {
cases,
},
computed: {
thecase: function() {
return this.cases.find(c => c.case_id === (this.case_id || ''))
}
}
and then you can use v-for on thecase.thread just like you would do for a data option like:
<li v-for="item in thecase.thread" :key="item.t_id">
{{ item.text }}
</li>
You can further modify it and use v-if & v-else to show a text like No cases were found with give case id in case there is no match found.
Lets assume I have an mongodb items collection looking like this (MongoLab):
{
"_id": {
"$oid": "531d8dd2e4b0373ae7e8f505"
},
"tags": [
"node",
"json"
],
"anotherField": "datahere"
}
{
"_id": {
"$oid": "531d8dd2e4b0373ae7e8f505"
},
"tags": [
"ajax",
"json"
],
"anotherField": "datahere"
}
I would like to get all items where a node is within the tags array.
I've tried the below, but no success - it is returning all items - no search performed?
Plunker demo : http://plnkr.co/edit/BYj09TOGyCTFKhhBXpIO?p=preview
// $route.current.params.id = "node" - should give me only 1 record with this tag
Restangular.all("items").customGET("", { "tags": $route.current.params.id });
Full example, return same record for both cases:
var all = db.all('items');
// GET ALL
all.getList().then(function(data) {
$scope.all = data;
console.log(data);
});
// SEARCH for record where "tags" has got "node"
all.customGET('', { "tags": "node"}).then(function(data) {
$scope.search = data;
console.log(data);
});
Any suggestion would be much appreciated.
According to Mongolab REST API Documentation you have to pass the query object with the q parameter. In your case it is q={"tags":"node"}.
Using Restangular it will be like this:
Restangular.all("items").customGET('', { q: {"tags": "node"}})
I am trying to populate a JQM ListView with a local JSON information. However, no list items are created. Any help would be appreciated. Here is my code:
JSON File Structure:
[
{
"name" : "test"
"calories" : "1000"
"fat" : "100"
"protein" : "100"
"carbohydrates" : "800"
},
{
"name" : "test2"
"calories" : "10000"
"fat" : "343"
"protein" : "3434"
"carbohydrates" : "4343"
}
]
HTML:
<div data-role="page" data-title="Search" id="searchPage">
<ul data-role="listview" data-inset="true" id="searchFood">
</ul>
</div>
JS:
(Updated)
$(document).on("pageinit", "#searchPage", function(){
$.getJSON("../JS/food.json", function(data){
var output = '';
$.each(data, function(index, value){
output += '<li>' +data.name+ '</li>';
});
$('#searchFood').html(output).listview("refresh");
});
});
First of all, the return JSON array is wrong, values (properties) should be separated by commas.
var data = [{
"name": "test",
"calories": "1000",
"fat": "100",
"protein": "100",
"carbohydrates": "800",
}, {
"name": "test2",
"calories": "10000",
"fat": "343",
"protein": "3434",
"carbohydrates": "4343",
}];
Second mistake, you should read value object returned by $.each() function not data array.
$.each(data, function (index, value) {
output += '<li>' + value.name + '</li>';
});
jQueryMobile only enhances the page once when it is loaded. When new data is added dynamically to the page, jQueryMobile must be made aware of the data for the data to be enhanced.
After extracting data from JSON array, append them then refresh listview to restyle newly added elements.
$('#searchFood').html(output).listview("refresh");
Demo
I am looking to develop locally with just a hardcoded JSON file. My JSON file is as follows (valid when put into JSON validator):
{
"contentItem": [
{
"contentID" : "1",
"contentVideo" : "file.mov",
"contentThumbnail" : "url.jpg",
"contentRating" : "5",
"contentTitle" : "Guitar Lessons",
"username" : "Username",
"realname" : "Real name",
"contentTags" : [
{ "tag" : "Guitar"},
{ "tag" : "Intermediate"},
{ "tag" : "Chords"}
],
"contentAbout" : "Learn how to play guitar!",
"contentTime" : [
{ "" : "", "" : "", "" : "", "" : ""},
{ "" : "", "" : "", "" : "", "" : ""}
],
"series" :[
{ "seriesVideo" : "file.mov", "seriesThumbnail" : "url.jpg", "seriesTime" : "time", "seriesNumber" : "1", "seriesTitle" : "How to Play Guitar" },
{ "videoFile" : "file.mov", "seriesThumbnail" : "url.jpg", "seriesTime" : "time", "seriesNumber" : "2", "seriesTitle" : "How to Play Guitar" }
]
},{
"contentID" : "2",
"contentVideo" : "file.mov",
"contentThumbnail" : "url.jpg",
"contentRating" : "5",
"contentTitle" : "Guitar Lessons",
"username" : "Username",
"realname" : "Real name",
"contentTags" : [
{ "tag" : "Guitar"},
{ "tag" : "Intermediate"},
{ "tag" : "Chords"}
],
"contentAbout" : "Learn how to play guitar!",
"contentTime" : [
{ "" : "", "" : "", "" : "", "" : ""},
{ "" : "", "" : "", "" : "", "" : ""}
],
"series" :[
{ "seriesVideo" : "file.mov", "seriesThumbnail" : "url.jpg", "seriesTime" : "time", "seriesNumber" : "1", "seriesTitle" : "How to Play Guitar" },
{ "videoFile" : "file.mov", "seriesThumbnail" : "url.jpg", "seriesTime" : "time", "seriesNumber" : "2", "seriesTitle" : "How to Play Guitar" }
]
}
]
}
I've gotten my controller, factory, and html working when the JSON was hardcoded inside the factory. However, now that I've replaced the JSON with the $http.get code, it doesn't work. I've seen so many different examples of both $http and $resource but not sure where to go. I'm looking for the simplest solution. I'm just trying to pull data for ng-repeat and similar directives.
Factory:
theApp.factory('mainInfoFactory', function($http) {
var mainInfo = $http.get('content.json').success(function(response) {
return response.data;
});
var factory = {}; // define factory object
factory.getMainInfo = function() { // define method on factory object
return mainInfo; // returning data that was pulled in $http call
};
return factory; // returning factory to make it ready to be pulled by the controller
});
Any and all help is appreciated. Thanks!
Okay, here's a list of things to look into:
1) If you're not running a webserver of any kind and just testing with file://index.html, then you're probably running into same-origin policy issues. See:
https://code.google.com/archive/p/browsersec/wikis/Part2.wiki#Same-origin_policy
Many browsers don't allow locally hosted files to access other locally hosted files. Firefox does allow it, but only if the file you're loading is contained in the same folder as the html file (or a subfolder).
2) The success function returned from $http.get() already splits up the result object for you:
$http({method: 'GET', url: '/someUrl'}).success(function(data, status, headers, config) {
So it's redundant to call success with function(response) and return response.data.
3) The success function does not return the result of the function you pass it, so this does not do what you think it does:
var mainInfo = $http.get('content.json').success(function(response) {
return response.data;
});
This is closer to what you intended:
var mainInfo = null;
$http.get('content.json').success(function(data) {
mainInfo = data;
});
4) But what you really want to do is return a reference to an object with a property that will be populated when the data loads, so something like this:
theApp.factory('mainInfo', function($http) {
var obj = {content:null};
$http.get('content.json').success(function(data) {
// you can do some processing here
obj.content = data;
});
return obj;
});
mainInfo.content will start off null, and when the data loads, it will point at it.
Alternatively you can return the actual promise the $http.get returns and use that:
theApp.factory('mainInfo', function($http) {
return $http.get('content.json');
});
And then you can use the value asynchronously in calculations in a controller:
$scope.foo = "Hello World";
mainInfo.success(function(data) {
$scope.foo = "Hello "+data.contentItem[0].username;
});
I wanted to note that the fourth part of Accepted Answer is wrong
.
theApp.factory('mainInfo', function($http) {
var obj = {content:null};
$http.get('content.json').success(function(data) {
// you can do some processing here
obj.content = data;
});
return obj;
});
The above code as #Karl Zilles wrote will fail because obj will always be returned before it receives data (thus the value will always be null) and this is because we are making an Asynchronous call.
The details of similar questions are discussed in this post
In Angular, use $promise to deal with the fetched data when you want to make an asynchronous call.
The simplest version is
theApp.factory('mainInfo', function($http) {
return {
get: function(){
$http.get('content.json'); // this will return a promise to controller
}
});
// and in controller
mainInfo.get().then(function(response) {
$scope.foo = response.data.contentItem;
});
The reason I don't use success and error is I just found out from the doc, these two methods are deprecated.
The $http legacy promise methods success and error have been deprecated. Use the standard then method instead.
this answer helped me out a lot and pointed me in the right direction but what worked for me, and hopefully others, is:
menuApp.controller("dynamicMenuController", function($scope, $http) {
$scope.appetizers= [];
$http.get('config/menu.json').success(function(data) {
console.log("success!");
$scope.appetizers = data.appetizers;
console.log(data.appetizers);
});
});
I have approximately these problem. I need debug AngularJs application from Visual Studio 2013.
By default IIS Express restricted access to local files (like json).
But, first: JSON have JavaScript syntax.
Second: javascript files is allowed.
So:
rename JSON to JS (data.json->data.js).
correct load command ($http.get('App/data.js').success(function (data) {...
load script data.js to page (<script src="App/data.js"></script>)
Next use loaded data an usual manner. It is just workaround, of course.
++ This worked for me. It's vanilla javascirpt and good for use cases such as de-cluttering when testing with ngMocks library:
<!-- specRunner.html - keep this at the top of your <script> asset loading so that it is available readily -->
<!-- Frienly tip - have all JSON files in a json-data folder for keeping things organized-->
<script src="json-data/findByIdResults.js" charset="utf-8"></script>
<script src="json-data/movieResults.js" charset="utf-8"></script>
This is your javascript file that contains the JSON data
// json-data/JSONFindByIdResults.js
var JSONFindByIdResults = {
"Title": "Star Wars",
"Year": "1983",
"Rated": "N/A",
"Released": "01 May 1983",
"Runtime": "N/A",
"Genre": "Action, Adventure, Sci-Fi",
"Director": "N/A",
"Writer": "N/A",
"Actors": "Harrison Ford, Alec Guinness, Mark Hamill, James Earl Jones",
"Plot": "N/A",
"Language": "English",
"Country": "USA",
"Awards": "N/A",
"Poster": "N/A",
"Metascore": "N/A",
"imdbRating": "7.9",
"imdbVotes": "342",
"imdbID": "tt0251413",
"Type": "game",
"Response": "True"
};
Finally, work with the JSON data anywhere in your code
// working with JSON data in code
var findByIdResults = window.JSONFindByIdResults;
Note:- This is great for testing and even karma.conf.js accepts these files for running tests as seen below. Also, I recommend this only for de-cluttering data and testing/development environment.
// extract from karma.conf.js
files: [
'json-data/JSONSearchResultHardcodedData.js',
'json-data/JSONFindByIdResults.js'
...
]
Hope this helps.
++ Built on top of this answer https://stackoverflow.com/a/24378510/4742733
UPDATE
An easier way that worked for me is just include a function at the bottom of the code returning whatever JSON.
// within test code
let movies = getMovieSearchJSON();
.....
...
...
....
// way down below in the code
function getMovieSearchJSON() {
return {
"Title": "Bri Squared",
"Year": "2011",
"Rated": "N/A",
"Released": "N/A",
"Runtime": "N/A",
"Genre": "Comedy",
"Director": "Joy Gohring",
"Writer": "Briana Lane",
"Actors": "Brianne Davis, Briana Lane, Jorge Garcia, Gabriel Tigerman",
"Plot": "N/A",
"Language": "English",
"Country": "USA",
"Awards": "N/A",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjEzNDUxMDI4OV5BMl5BanBnXkFtZTcwMjE2MzczNQ##._V1_SX300.jpg",
"Metascore": "N/A",
"imdbRating": "8.2",
"imdbVotes": "5",
"imdbID": "tt1937109",
"Type": "movie",
"Response": "True"
}
}
I want to make Nested list of shopping categories using data provided by server which looks something like this:
{
"status":{"statusCode":15001},
"data":[
{"itemId":1, "name":"Men", "subCategories":[
{"itemId":2, "name":"Clothes", "subCategories":[
{"itemId":3, "name":"Formals", "leaf":true,"subCategories":[]},
{"itemId":4, "name":"Casual", "leaf":true,"subCategories":[]},
{"itemId":5, "name":"Sports", "leaf":true,"subCategories":[]}
]},
{"itemId":6, "name":"Accessories", "subCategories":[
{"itemId":7, "name":"Formals", "leaf":true,"subCategories":[]},
{"itemId":8, "name":"Casual", "leaf":true,"subCategories":[]},
{"itemId":9, "name":"Sports", "leaf":true,"subCategories":[]}
]}
]},
{"itemId":10, "name":"Women", "subCategories":[
{"itemId":11, "name":"Clothes", "subCategories":[
{"itemId":12, "name":"Formals", "leaf":true,"subCategories":[]},
{"itemId":13, "name":"Casual", "leaf":true,"subCategories":[]},
{"itemId":14, "name":"Ethnic", "leaf":true,"subCategories":[]}
]},
{"itemId":15, "name":"Shoes", "subCategories":[
{"itemId":16, "name":"Hells", "leaf":true,"subCategories":[]},
{"itemId":17, "name":"Wedges", "leaf":true,"subCategories":[]},
{"itemId":18, "name":"Sports", "leaf":true,"subCategories":[]}
]}
]}
]
}
Since tree structure is wrapped in data element and children are wrapped in subCategories tag which is different from data so I wanted to pre-process this data such that it can be used by Nested List directly by making response like this:
{
"categories":[
{"itemId":1, "name":"Men", "categories":[
{"itemId":2, "name":"Clothes", "categories":[
{"itemId":3, "name":"Formals", "leaf":true,"categories":[]},
{"itemId":4, "name":"Casual", "leaf":true,"categories":[]},
{"itemId":5, "name":"Sports", "leaf":true,"categories":[]}
]},
{"itemId":6, "name":"Accessories", "categories":[
{"itemId":7, "name":"Formals", "leaf":true,"categories":[]},
{"itemId":8, "name":"Casual", "leaf":true,"categories":[]},
{"itemId":9, "name":"Sports", "leaf":true,"categories":[]}
]}
]},
{"itemId":10, "name":"Women", "categories":[
{"itemId":11, "name":"Clothes", "categories":[
{"itemId":12, "name":"Formals", "leaf":true,"categories":[]},
{"itemId":13, "name":"Casual", "leaf":true,"categories":[]},
{"itemId":14, "name":"Ethnic", "leaf":true,"categories":[]}
]},
{"itemId":15, "name":"Shoes", "categories":[
{"itemId":16, "name":"Hells", "leaf":true,"categories":[]},
{"itemId":17, "name":"Wedges", "leaf":true,"categories":[]},
{"itemId":18, "name":"Sports", "leaf":true,"categories":[]}
]}
]}
]
}
For this I was overriding getResponseData of reader but this method never gets called and no records are loaded in store. What am I doing wrong?
Here is my store:
Ext.define('MyTabApp.store.CategoriesStore',{
extend:'Ext.data.TreeStore',
config:{
model : 'MyTabApp.model.Category',
autoLoad: false,
storeId : 'categoriesStore',
proxy: {
type: 'ajax',
url: Properties.CONFIG_SERVICE_BASE_URL+'topnav/getall',
reader: {
type: 'json',
getResponseData: function(response) {
console.log("in getResponseData"); // Never logged in console
var rText = response.responseText;
var processed = Helper.replaceAll("data","categories",rText);
processed = Helper.replaceAll("subCategories","categories",processed);
var respObj = Ext.JSON.decode(processed);
return respObj.categories;
}
}
},
listeners:{
load: function( me, records, successful, operation, eOpts ){
console.log("categories tree loaded");
console.log(records); // This prints blank array
}
}
}
});
and here is model:
Ext.define('MyTabApp.model.Category', {
extend : 'Ext.data.Model',
config : {
idProperty : 'itemId',
fields : [
{name : 'itemId',type : 'int'},
{name : 'name',type : 'string'}
]
}
});
This is the list:
Ext.define('MyTabApp.view.CategoriesList', {
extend: 'Ext.dataview.NestedList',
alias : 'widget.categorieslist',
config: {
height : '100%',
title : 'Categories',
displayField : 'name',
useTitleAsBackText : true,
style : 'background-color:#999 !important; font-size:75%',
styleHtmlContent : true,
listConfig: {
itemHeight: 47,
itemTpl : '<div class="nestedlist-item"><div style="position:absolute; left:10px; top:10px; color:#222; font-size:130%">{name}</div></div>',
height : "100%"
}
},
initialize : function() {
this.callParent();
var me = this;
var catStore = Ext.create('MyTabApp.store.CategoriesStore');
catStore.load();
me.setStore(catStore);
}
});
What is best practice to process & format received data if it is not in the format we want and we don't have control over services?
I dont think you can attach getResponseData to reader's configuration. In past I have used the following approach.
Create an override of Ext.data.reader.Json like below. But the downside is that this will be called for all your proxies using json reader. and then add YourApp.override.data.reader.Json in the requires section of your application.
Ext.define('YourApp.override.data.reader.Json', {
override: 'Ext.data.reader.Json',
'getResponseData': function(response) {
// your implementation here
}
Alternatively you can make a Ext.Ajax.request and on success handler parse the data the way you want and then set the data in your store. You can also write this code in the "refresh" event or "beforeload" event of the store and return false to cancel the action