how do take last value from one property in JSON in angularjs - angularjs

so I have chatting application, with this JSON:
{
"561c": [{
"from": "561c",
"fromname": "ryan",
"to": "sasa",
"messgae": "hey"
}, {
"from": "5512",
"fromname": "sasa",
"to": "ryan",
"messgae": "hey too"
}]
}
but this JSON will always add up when the users send messages. I want to take the the last value just from "message" to use this value in my Text-to-Speech code, how do I write the code?
and this is my Text-to-Speech:
$scope.speakText = function() {
TTS.speak({
text: ***this place is for the code***,
locale: 'en-GB',
rate: 0.75
}, function () {
// handle the succes case
}, function (reason) {
// Handle the error case
});
};

use forEach loop on the object '561c' like
var messArray = [];
561c.forEach(function(obj){
messArray.push(obj.message)})
var text = messArray.join();
You will have all the message in messArray.
If i have understood your question correct.

//get the last element of array
var lastIndex = 561c.length();
var lastObj = 561c[lastIndex];
//get message from last object of array 561c
var lastMessage = lastObj.message;
and you got what you want(y);

You can use the "pluck" function of underscore.js - http://underscorejs.org/#pluck
_.pluck(your array of JSONs, 'messgae');

You can pass $scope to your function then pass 561c you will get object then you can index message in it
Example :
$scope.chat = {
"561c": [{
"from": "561c",
"fromname": "ryan",
"to": "sasa",
"messgae": "hey"
}, {
"from": "5512",
"fromname": "sasa",
"to": "ryan",
"messgae": "hey too"
}]
}
angular.module('app',[]).controller('myctrl', function($scope, data){
$scope.561c = data.messgae;
}

Related

angularjs undefined resource

I am new in angularJs, I am trying to have my first steps in developping an application and I am facing a problem.
I am calling an external resource that return an object json via $resource.get(), in the callBack I am getting the correct values, but in the service the values are undefined, the problem is when I am printing the resource in the console the result has the correct values.
my json object :
{
"readOnly": false,
"questions": [
{
"questionId": "0",
"questionTitle": "question0",
"isMondatory": true,
"responseList": [
{
"questionId": "0",
"questionTitle": null,
"responseId": "00",
"responseTitle": "response00"
},
{
"questionId": "0",
"questionTitle": null,
"responseId": "01",
"responseTitle": "response01"
},
{
"questionId": "0",
"questionTitle": null,
"responseId": "02",
"responseTitle": "response02"
},
{
"questionId": "0",
"questionTitle": null,
"responseId": "03",
"responseTitle": "response03"
}
]
},
{
"questionId": "1",
"questionTitle": "question1",
"isMondatory": true,
"responseList": [
{
"questionId": "1",
"questionTitle": null,
"responseId": "10",
"responseTitle": "response10"
},
{
"questionId": "1",
"questionTitle": null,
"responseId": "11",
"responseTitle": "response11"
},
{
"questionId": "1",
"questionTitle": null,
"responseId": "12",
"responseTitle": "response12"
},
{
"questionId": "1",
"questionTitle": null,
"responseId": "13",
"responseTitle": "response13"
}
]
}
my controller is
app.controller('mycontroller', function ($scope,myservice) {
$scope.infos = null;
$scope.infos = myservice.getInfo();
}
my service is :
angular.module('xxxx').factory('myservice', function($window,$resource,$routeParams,$http,apicallservice) {
// Public API here
return {
getInfo : function(){
var result=null;
var url = "myUrl";
result = apicallservice.GetApiCall(url,$routeParams);
console.log(result.readOnly); // print undefined => KO
return result;
},
//.... other functions
my apicallservice :
angular.module('xxxx')
.factory('apicallservice', function ($http,$resource) {
var result;
// Public API here
return {
GetApiCall: function (url,obj) {
// resource
var resource = $resource(url,{param1:obj});
// cal the api
result = resource.get(function(callBack) {
console.log(callBack.readOnly); => print false => OK
return callBack;
}, function(error) {
console.log(error);
return error;
});
return result;
},
PostApiCall : function(url,obj){
result = $http.post(url,obj).then(
function (response) {
console.log(response);
}, function (error) {
console.log(error);
});
}
};
});
please can you help me ?
thanks in advance.
From angularjs api documentation for $resource
It is important to realize that invoking a $resource object method
immediately returns an empty reference (object or array depending on
isArray). Once the data is returned from the server the existing
reference is populated with the actual data. This is a useful trick
since usually the resource is assigned to a model which is then
rendered by the view. Having an empty object results in no rendering,
once the data arrives from the server then the object is populated
with the data and the view automatically re-renders itself showing the
new data. This means that in most cases one never has to write a
callback function for the action methods.
So basically for
$scope.infos = myservice.getInfo();,
result will have an empty object/array reference. Since the call is asynchronous, the next line(console.log(result.readOnly)) gets called immediately and you will get undefined. Only when the underlying get/post call actually completes, variable result will be populated with the value from the server
I found what was going wrong, in the controller I had to add then() :
instead of this :
app.controller('mycontroller', function ($scope,myservice) {
$scope.infos = null;
$scope.infos = myservice.getInfo();
}
do this :
app.controller('mycontroller', function ($scope,myservice) {
$scope.infos = null;
myservice.getInfo().then(function(data) {
$scope.infos = data;
});
}
this resolved the problem.

Angular JS : How to create a Array dynamically by reading a JSON Array

I have a JSON as below
[
{
"id": 1000,
"name": "Open"
},
{
"id": 1000,
"name": "Ravi"
},
{
"id": 1000,
"name": "POOO"
}]
On click of a button I am trying to create a Array by reading all the names from the Array
I have tried as follwoing
var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function($scope)
{
$scope.formData = function()
{
var aa = $scope.tickets.length;
$scope.products = $scope.tickets.name;
alert($scope.products);
};
$scope.tickets = [
{
"id": 1000,
"name": "Open"
},
{
"id": 1000,
"name": "Ravi"
},
{
"id": 1000,
"name": "POOO"
}]
});
Currently i am getting undefined , could you please let me know how to do this
Thanks in advance
http://jsfiddle.net/9fR23/434/
I dont want tradional style using a for loop to read .
Could you please suggest a professional approach .
If you won't to use a loop to read, then you can use Underscore.js.
By using Underscore.js you can do this as below. before that you need to check this link for how use underscore inside angular controllers.
var result = _.map([{ id: 1, name: "vinit"},{ id: 2, name: "jaimin"}], function (v) {
return v.name;
});
alert(JSON.stringify(result));
jsfilddle
You can make a loop to read all data in array and push them to your new array:
$scope.formData = function()
{
$scope.products = [];
var aa = $scope.tickets.length;
angular.forEach($scope.tickets, function(value, key) {
$scope.products.push(value.name);
});
alert($scope.products);
};
Updated fiddle

Print JSON array in expected format

This is the code to get the details from my table.
function listshops(callback)
{
var array=[3,4];/*shopId*/
async.each(array,function(dat,callback){
async.parallel([
function(callback){
client.connection.query('select * from shop where shopId=?',dat,function(err,data1){
callback(null,data1);
});
},
function (callback) {
client.connection.query('select * from image where shopId=?',dat,function(err,data2){
callback(null,data2);
});
}
],
function(err,data)
{
var result = data.reduce(function(prev, curr) { /*merging the array*/
return prev.concat(curr);
});
console.log(result);
});
});
}
I got an output like this:: http://i.stack.imgur.com/NVUAu.png
i want to print my result in the below format:
{
"shops": [
{
"shopId": "3",
"shopName": "1",
"address": "abc",
"contactNumber":"1234"
"images": [
{
"imageId": "1",
"shopId": "3",
"imageUrl": "aaa",
},
{
"imageId": "2",
"shopId": "3",
"imageUrl": "bbb",
},
]
},
{
"shopId": "4",
"shopName": "2",
"address": "bbb",
"contactNumber":"1234"
"images": [
{
"imageId": "3",
"shopId": "4",
"imageUrl": "ccc",
},
{
"imageId": "4",
"shopId": "4",
"imageUrl": "ddd",
},
]
},
]
I got the values but some confusions in fetching the values.
You have two nested async tasks here, parallel and each.
Parallel takes care of getting the shop information and the images for one shop and calls the final callback with a two element array that has the results for your tasks.
This is your final callback for parallel:
function(err,data)
{
var result = data.reduce(function(prev, curr) { /*merging the array*/
return prev.concat(curr);
});
console.log(result);
});
data should be a two element array, where element 0 is the shop, and element 1 are the images. You just concatenate these together. If you want your images in the desired format, you should do data[0].images = data[1] to add the images key to your shop.
That so far is for one shop. Then there is the outer each loop. You are currently not giving this a final callback and not doing anything with the result.
Something like this:
function listshops(callback)
{
var array=[3,4];/*shopId*/
async.each(array,function(dat,eachCallback){
async.parallel([
function(parallelCallback){
client.connection.query('select * from shop where shopId=?',dat,function(err,data1){
parallelCallback(null,data1);
});
},
function (parallelCallback) {
client.connection.query('select * from image where shopId=?',dat,function(err,data2){
parallelCallback(null,data2);
});
}
],
// this is the final callback for parallel
function(err,parallelResult)
{
// construct one shop
var shop = parallelResult[0];
shop.image = parallelResult[1];
// pass the shop info back as a result to each
eachCallBack(shop);
});
},
// this is the final callback for each
function(err, eachResult) {
// eachResult is an array with the shops returned from parallel callback
var result = {
shops: eachResult
}
return result
}
);
}
I couldn't test this, so don't consider it an exact solution, but an explanation. I renamed your variables for better understandability, you don't have to do that in your code. The key thing to keep in mind is that you have two nested tasks here, like a nested loop and you also have to deal with the results on two levels.

How to filter following JSON with ionic filter bar

Using Ionic Filter Bar for implementing search in ionic app, I need to to search on "parent_type" and "child_type" from following json,
{
"status": {
"code": 200,
"message": "all data grabbed successfully",
"cause": ""
},
"ParentData": [
{
"id": 67,
"parent_type": "Parent Type",
"child": [
{
"id": 86,
"child_type": "Child Type"
},
{
"id": 93,
"child_type": "Child Type1"
}
]
},
{
"id": 68,
"parent_type": "Parent Type 1",
"child": [
{
"id": 87,
"child_type": "Child Type 1"
},
{
"id": 94,
"child_type": "Child Type 2"
}
]
}
]
}
its working fine for "parent_type" with following code
Here is the filter code
$scope.showFilterBar = function () {
filterBarInstance = $ionicFilterBar.show({
//setting parentData in following way after rest service call
//$scope.parentData = jsondata.ParentData
items: $scope.parentData,
update: function (filteredItems, filterText) {
$scope.parentData = filteredItems;
if (filterText) {
console.log(filterText);
}
},
filterProperties: ['parent_type']
});
};
But not able to search on "child_type"
So is there any way to set filterProperties so it will work for both "parent_type" and "child_type" or any other way to search this Json?
Thanks.
You should remove the "filterProperties" key and then add "expression" key.
Your "filterBarInstance" will be something like this:
$scope.showFilterBar = function () {
filterBarInstance = $ionicFilterBar.show({
items: $scope.parentData,
update: function (filteredItems, filterText) {
$scope.parentData = filteredItems;
if (filterText) {
console.log(filterText);
}
},
expression: function(filterText,value,index,array){
// This function is called for every ParentData object.
// "value" will be the current ParentData object,
// you'll need to iterate over all the "child" array in order to
// check if any of the "child_type" keys contains the "filterText"
// so if "parent_type" contains the "filterText" and any(? or all)
// of the the "child[x].child_type" values also contains the
// "filterText" return true
}
});
};
Check https://github.com/djett41/ionic-filter-bar for the original documentation.
Sorry for my english :)

how to convert json data in angularJs

I am getting json data from service. this is my json data:
[
{
"id":"1",
"body":"sample text",
"read":"true",
"checked":"true"
},
{
"id":"2",
"body":"sample text",
"read":"true",
"checked":"false"
}
]
I want to read it as id=2,read=true , how to convert this json string format to actual datatype.
You need to loop through your array and process the boolean values that are currently represented as text. In the example below, I've used JSON.parse to process the boolean text and then saved the result back to the read variable. Save applies to id but I've gone for parseInt in this case.
.controller('MyCtrl', function($scope) {
//example mock http call
function getHttpData() {
return [{
"id": "1",
"body": "sample text",
"read": "false",
"checked": "true"
}, {
"id": "2",
"body": "sample text",
"read": "true",
"checked": "false"
}];
}
function getData() {
var data = getHttpData();
//process array as required
data.forEach(function(value) {
value.id = parseInt(value.id);
value.read = JSON.parse(value.read);
});
return data;
}
$scope.data = getData();
});
Fiddle here:
https://jsfiddle.net/tmakin/cvzc4mks/5/
You want to pass your JSON string to the JSON.parse() function. That will return a JavaScript object that you can use normally.

Resources