TypeError: value is undefined angularjs - angularjs

I have a controller
.controller('ArticlesCtrl', function($scope) {
$scope.sum = function(value) {
return value.reduce(function(total, article) {
return total + article.price;
}, 0);
};
});
and json
[
{"id": "1", "name": "Pizza Vegetaria", "price": 5 },
{"id": "2", "name": "Pizza Salami", "price": 5.5 },
{"id": "3", "name": "Pizza Thunfisch", "price": 6 },
{"id": "4", "name": "Pizza Salami", "price": 5.5 },
{"id": "5", "name": "Pizza Thunfisch", "price": 6 }
]
It works and counts 28 but i get an error in the firebug
watch.js (строка 59)
GET http://192.168.1.136:6543/www/an/articles.json
angular.js (строка 10413)
Error: value is undefined
$scope.sum#http://192.168.1.136:6543/www/an/app.js:43:36
anonymous/fn#https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js line 13036 > Function:2:276
expressionInputWatch#https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js:14014:31
$RootScopeProvider/this.$get</Scope.prototype.$digest#https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js:15548:34
$RootScopeProvider/this.$get</Scope.prototype.$apply#https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js:15824:13
done#https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js:10263:36
completeRequest#https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js:10435:7
requestLoaded#https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js:10376:1
return logFn.apply(console, args);
Somebody has an idea?
I call the code in the template with {{ sum(articles) }}.

What happens is that since you use
{{ sum(articles) }}
and load data with AJAX request, at the first cycle of template evaluation articles are not yet available. So your sum function tries to call reduce method of the undefined.
The simplest solution is to make sum function return 0 if no articles are available:
$scope.sum = function(value) {
return value && value.reduce(function(total, article) {
return total + article.price;
}, 0) || 0;
};

Related

Decode the encoded value directly in view/html

I am submitting a form for job posting and have skills like C# which escape in my rest API. So I encoded the skills and sending to backend.
"skills":encodeURIComponent(skills)
now when I get back the skills I am doing decodeURIComponent for my skills
$scope.skills = decodeURIComponent(skills);
but this wont work with array of datas, when I want to fetch list of jobs , the datas comes in array , my array has almost 15 key values , which will be used in table some way. Writing a new array and pushing each values into array again pushing decoded skills a big process.
Is any solution to directly decoded the value in view , that is html
I tried {{decodeURIComponent(item.skills) }} but no luck.
sample Data ::
{
"json": {
"response": {
"statusmessage": "Success",
"count": 59,
"data": [
{
"employerId": 2,
"employerEmail": "sumit#infosoftjoin.in",
"employerName": "SumitKumar",
"companyName": "Infosoftjoin%20pvt%20ltd.",
"jobId": 142,
"jobTitle": "Test%20case%201",
"jobDescription": "<p>ahdu%29%28#*%29*W%29%28*%29E%26%3D--%3D</p>",
"link": "http://www.infosoftjoin.in",
"numberOfPositions": 5,
"createdTime": "18-May-2018",
"lastUpdatedTime": "18-May-2018",
"consumedCredits": 44,
"location": {
"city": "North And Middle Andaman",
"state": "Andaman and Nicobar Islands",
"country": "India"
},
"skills": [
"C%23.NET"
],
"approved": 1,
"status": "Approved"
},
{
"employerId": 2,
"employerEmail": "sumit#infosoftjoin.in",
"employerName": "SumitKumar",
"companyName": "Infosoftjoin%20pvt%20ltd.",
"jobId": 130,
"jobTitle": "New%20job",
"jobDescription": "hryuyurfkituo8",
"link": "http://www.infosoftjoin.in",
"numberOfPositions": 5,
"createdTime": "16-May-2018",
"lastUpdatedTime": "16-May-2018",
"consumedCredits": 93,
"location": {
"city": "Nicobar",
"state": "Andaman and Nicobar Islands",
"country": "India"
},
"skills": [
"APACHE TOMCAT"
],
"approved": 1,
"status": "Approved"
}
]
}
}
}
encodeURIComponent is a JavaScript built-in function, you can not access it directly in your AngularJs template. Convert that into a $scope function then try accessing from AngularJs template.
I would suggest you to have a filter for the same instead of $scope function.
Filter:
app.filter('decodeFilter', function() {
return function(input) {
return decodeURIComponent(input);
};
});
Template:
{{item.skills | decodeFilter}}
If still you want that as $scope function then try below code:
Controller:
$scope.decodeComponent=function(value){
return decodeURIComponent(value);
}
Template:
{{decodeComponent(item.skills)}}
Also, please check this plunker for sample scenario with the above examples.

How can I change the attribute in dataset of Fusionchart?

Hi I am implementing a chart in my Angularjs Application, You can see this plunker http://jsfiddle.net/fusioncharts/73xgmacm/ The thing which I want to achieve is to change the value attribute to profit. How can I do this ? I want to display profit not values.
Regards
After 2 days I finally find out the answer. The thing is You cannot change the Fusionchart attribute value but you can change the attribute of your API once you fetched. I used a loop after I fetched the API and replace the 'profit' attribute with value in this way I made the chart. Yes The thing which i had been ignoring was the use of 'variable' instead of scope. If you see this example you would understand Example Here. I am sharing my code May be it helps someone else too.
Give below is my json array which i called tps.json
[
{
"index": "1",
"variantoption": "fan-green",
"company": "sk fans",
"quantity": "650",
"profit": "78296",
"loss": "8457",
"year": "2016"
},
{
"index": "2",
"variantoption": "fan-white",
"company": "al ahmed fans",
"quantity": "450",
"profit": "78296",
"loss": "8457",
"year": "2016"
},
{
"index": "3",
"variantoption": "fan-purple",
"company": "asia fans",
"quantity": "350",
"profit": "78296",
"loss": "8457",
"year": "2016"
},
{
"index": "4",
"variantoption": "fan-yellow",
"company": "falcon fans",
"quantity": "250",
"profit": "78296",
"loss": "8457",
"year": "2016"
}
]
and here is my controller
$http.get('js/tps.json').success(function (data) {
var chartdata = data;
var arrLength = chartdata.length;
console.log(arrLength);
for (var i = 0; i < arrLength; i++) {
if (chartdata[i]['profit'] && chartdata[i]['index']) {
chartdata[i].value = chartdata[i].profit;
delete chartdata[i].profit;
chartdata[i].label = chartdata[i].index;
delete chartdata[i].index;
console.log(chartdata);
}
}
console.log(chartdata);
FusionCharts.ready(function () {
var tps = new FusionCharts({
type: 'column2d',
renderAt: 'chart-container',
width: '500',
height: '300',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Monthly",
"xaxisname": "Month",
"yaxisname": "Revenue",
"numberprefix": "$",
"showvalues": "1",
"animation": "1"
},
"data" : chartdata
}
});
tps.render();
});
}
);
}
-Stay foolish stay hungry

how to do $filter with more then one expression and comparator in angularjs

i want to filter in angular controller with two expression and two comparator function my code with loop is working fine
angular.forEach(vm.campaignData, function (value) {
if (value.startTime < today && value.endTime > today) {
vm.campaignFilteredData.push(value);
}
});
but i want with $filter but it is not working
vm.campaignFilteredData =$filter('filter')(vm.campaignData, {startTime : today , endTime: today} ,
function(actual, expected ) { return actual < expected;},function(actual, expected ) { return actual > expected;});
my data is like this
[{
"name": "Levis Marketing Event Vadodra Himalaya Mall",
"tenantId": 1,
"locationId": 5,
"createdByName": "sg_area_manager",
"startTime": 1462300200000,
"endTime": 1462473000000,
"description": "This event for Marketing Levis Vadodra Himalaya Mall",
"metricIds": [],
"comparisionStartTs": 0,
"comparisionEndTs": 0
},
{
"name": "Levis Festival Event Vadodra Himalaya Mall",
"tenantId": 1,
"locationId": 5,
"createdByName": "sg_area_manager",
"startTime": 1462300200000,
"endTime": 1462473000000,
"description": "This event for Festival Levis Vadodra Himalaya Mall",
"metricIds": [],
"comparisionStartTs": 0,
"comparisionEndTs": 0
}]
Not the ideal solution, but it gets the job done. Better create your own angular filter though.
https://jsfiddle.net/ygL8rnb8/
vm.campaignFilteredData = $filter('filter')(vm.campaignData,
function(value) {
if (value.startTime < today && value.endTime > today) {
return true;
}
}
);

Strange behavior in angularjs

I have a Home page where I display set of data fetched from a $http.get function.
Well, the first time the page loads, it's displayed perfectly, but if you reload the page, it arises the following error:
angular.js:13550 SyntaxError: Unexpected token < in JSON at position 695
at Object.parse (native)
Now, if I go to another page and come back to Home page, it works fine. And if I reload again, it arises the same error.
I'm struggling trying to guess what's happening.
Here I post the init function:
$scope.init = function() {
functions.loading($scope.loading, true);
$scope.$on('loading', function(evt, value) {
$scope.loading.state = value;
});
angular.element(document).ready(function () {
searchService.search_stats().then( function(response) {
FusionCharts.ready(function(){
var last7days = new FusionCharts({
"type": "column2d",
"renderAt": "last7days",
"width": "100%",
"height": "300",
"dataFormat": "json",
"dataSource": {
"chart": {
"caption": "Volume of Searches - Graph",
"subCaption": "Last 7 days",
"xAxisName": "Last 7 days",
"yAxisName": "Volume of searches",
"theme": "fint"
},
"data": response.data.last7days
}
});
last7days.render();
var search_countries = new FusionCharts({
"type": "maps/world",
"renderAt": "search_countries",
"width": "100%",
"height": "400",
"dataFormat": "json",
"dataSource": {
"chart": {
"caption": "Search Volume by Country - Graph",
"subcaption": "Last 7 days ",
"entityFillHoverColor": "#cccccc",
"numberScaleValue": "1,1000,1000",
"numberScaleUnit": "K,M,B",
"numberPrefix": "$",
"showLabels": "1",
"theme": "fint"
},
"colorrange": {
"minvalue": "0",
"startlabel": "Low",
"endlabel": "High",
"code": "#e44a00",
"gradient": "1",
"color": [
{
"maxvalue": response.data.max/2,
"displayvalue": "Average",
"code": "#f8bd19"
},
{
"maxvalue": response.data.max,
"code": "#6baa01"
}
]
},
"data": response.data.countries
}
});
search_countries.render();
functions.loading($scope.loading, false);
});
});
functions.containerResize();
});
search_stats is in a Factory:
search_stats: function(a) {
return $http.get('/api/myFunctions/search_stats/', {cache:false});
}
Any idea?
Well,
Now, at least, I could guess what's happening.
For some strange circumstance, in Chrome was activated Development mode and when switch it off, the page works fine and no error arises now.

AngularJs filter is not working correctly

Please see the link
http://plnkr.co/edit/Cn0sNDGEkPOzV19ye8NW?p=preview
I have changed my JSON, then I can't able to filter the data.
var result = $filter('filter')(foo.results, {id:2426})[0];
if you limit on your JSON data
and you can make sure the data property value is num
maybe you can try this ...
var foo = {
"count": 70,
"language": "en",
"0": {
"id": "2420",
"name": "Medical Center"
},
"1": {
"id": "7840",
"name": "Conference Room"
},
"2": {
"id": "2426",
"name": "Deck 5 Starboard"
}
};
foo.results = [];
for(var property in foo){
if(property == parseInt(property, 10).toString()){
foo.results.push(foo[property]);
}
}
var result = $filter('filter')(foo.results, {id:2426})[0];
$scope.name = result.name;
wish help !!

Resources