Why local version of Angular app outputs error? - angularjs

I created a local version of this example.
This example works both with Angular 1.3 and 1.5 in a Codepen.
But there's an error in a console in a local version.
The code is the same:
angular.module("winnieApp", []);
angular.module("winnieApp").controller("winnieCtrl", ['$scope',
'$filter', function($scope, $filter){
$scope.friendsArr = [{"id": 1, "name":"Winnie", "age": 76, "food": "hunny"},
{"id": 2, "name":"Piglet", "age": 43, "food": "grains"},
{"id": 3, "name":"Tigger", "age": 52, "food": "meat"},
{"id": 4, "name":"Rabbit", "age": 34, "food": "carrot"},
{"id": 5, "name":"Eeyore", "age": 63, "food": "grass"}];
$scope.search = {
setFilter: function(method){ $scope.search.currentFilter =
$scope.search[method]; },
allage: function(data){ return true; },
ageLow: function(data){ return data.age < 50; },
ageHeight: function(data){ return data.age >= 50; },
};
}]);

Solved. There was 'ng-app="countryApp"' in my HTML tag.

Related

How to create an array from json ionic

Below is the data i get from the rest API
{
"memberdetails":[
{
"id":46,
"customername":"Zack",
"phoneno":"1323223232",
"nickname":"Zack",
"regdate":"2017-12-27 18:38:36.185829",
"groupname":"Test group",
"regid":36,
"groupdesc":"Test Test test",
"groupicon":"new",
"tamount":"3100"
},
{
"id":46,
"customername":"Carol",
"phoneno":"254721493487",
"nickname":"Caro",
"regdate":"2017-12-28 23:47:22.317687",
"groupname":"Test",
"regid":36,
"groupdesc":"Test Test Test",
"groupicon":"new",
"tamount":"130"
}
]
}
From the above data i want to populate 2 arrays as i want to plot a graph in the below format. The lineChartData array should pick the tamount and the lineChartLabels Array should pick the customenames. Thank you.
public lineChartData:Array<any> = [{data: [15, 29, 24, 21, 26, 15, 10], label: 'Opening/Time'}];
public lineChartLabels:Array<any> = ["Dan","Were","Kibe","Zack","Evah","Chris","Jess"];
angular.module('testapp', [])
.controller('TestCtrl', function(){
this.inputData = {
"memberdetails": [
{
"id": 46,
"customername": "Zack ",
"phoneno": "1323223232",
"nickname": "Zack ",
"regdate": "2017-12-27 18:38:36.185829",
"groupname": "Test group ",
"regid": 36,
"groupdesc": "Test Test test ",
"groupicon": "new ",
"tamount": "3100"
},
{
"id": 46,
"customername": "Carol ",
"phoneno": "254721493487",
"nickname": "Caro ",
"regdate": "2017-12-28 23:47:22.317687",
"groupname": "Test ",
"regid": 36,
"groupdesc": "Test Test Test ",
"groupicon": "new ",
"tamount": "130"
}
]
};
this.expectedOutput = {
"lineChartData": [
{
"data": [
15,
29,
24,
21,
26,
15,
10
],
"label": "Opening\/Time"
}
],
"lineChartLabels": [
"Dan",
"Were",
"Kibe",
"Zack",
"Evah",
"Chris",
"Jess"
]
}
this.computedLineChartData = [{data:[],label:"Opening\/Time"}];
this.computedLineChartLabels = [];
for(var i=0;i<this.inputData.memberdetails.length; i++){
var curMember = this.inputData.memberdetails[i];
this.computedLineChartData[0].data.push(curMember.tamount);
this.computedLineChartLabels.push(curMember.customername);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<div ng-app="testapp" ng-controller="TestCtrl as tc">
<pre>{{tc|json}}</pre>
</div>
In AngularJs we have function like angular.fromJson(data) which returns output in form of array . So you can easily convert json to array.

how do i access deeply nested json object in angularjs

Here, I am suppose to access the top level market details from the Json data on the first page which I'm able to although Im not able to access the sub level market details. Im suppose to display the sub level market names on the next page.
$scope.myData = {
"market": [{
"mid": 3,
"mname": "mark1",
"submarket": [{
"id": 20,
"name": "val1"
}, {
"id": 24,
"name": "val2",
"submarket": [{
"id": 26,
"name": "val21"
}]
}]
"market": [{
"mid": 4,
"name": "mark1.1",
"submarket": [{....
}]
}]
}, {
"mid": 6,
"mname": "mark2",
}]
};
$scope.markname = []; /*stores top level markets*/
angular.forEach($scope.myData.market, function(org) {
$scope.markname.push(org)
}) /*works fine and has the details of market (mid:3 and mid:6)*/
$scope.submark = [];
angular.forEach($scope.markname.submarket, function(sorg) {
$scope.submark.push(sorg)
}) /*doesn't store anything*/
It should be:
$scope.submark = [];
angular.forEach($scope.markname, function(sorg) {
angular.forEach(sorg.submarket, function(subsorg) {
$scope.submark.push(subsorg)
});
});
JSFiddle
$scope.markname is an array and your pushing items into it on your first forEach, however in the second your trying to access the property submarket. This doesn't exist on the markname array, it exists on each item within the array.
Ive done my example using the native forEach there's no need for angular to get involved here at all, it also hides the undefined issue, as the native is available of the array prototype it throws an exception if you try to call it of undefined, whilst angular happily accepts undefined and continues.
So a simple fix would be
markname.forEach(function(sorg) {
if (sorg.hasOwnProperty('submarket')) {
submark.push(sorg.submarket);
}
});
See fiddle: https://jsfiddle.net/0y6r0mw1/
edit: Its worth noting this will produce a multidimensional array, if this is not wanted you can concat them all together with something like:
submark.push.apply(submark, sorg.submarket);
The json data that you have shared, is improper. Please go through this demo.
HTML:
<div ng-app="app" ng-controller="test">
</div>
JS:
var app = angular.module('app', []);
app.controller('test', function ($scope) {
$scope.myData = {
"market": [{
"mid": 3,
"mname": "mark1",
"submarket": [{
"id": 20,
"name": "val1"
}, {
"id": 24,
"name": "val2",
"submarket": [{
"id": 26,
"name": "val21"
}]
}, {
"mid": 4,
"name": "mark1.1",
"submarket": [{
"id": 27,
"name": "val221"
}]
}]
}, {
"mid": 6,
"mname": "mark2",
}]
};
$scope.markname = []; /*stores top level markets*/
angular.forEach($scope.myData.market, function (org) {
$scope.markname.push(org)
}) /*works fine and has the details of market (mid:3 and mid:6)*/
console.log('markname', $scope.markname);
$scope.submark = [];
angular.forEach($scope.markname, function (sorg) {
angular.forEach(sorg.submarket, function (subM) {
$scope.submark.push(subM)
})
})
console.log('submark', $scope.submark);
});
function iterate(obj) {
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] == "object") {
iterate(obj[property]);
}
else {
console.log(property + " " + obj[property]);
}
}
}
}
iterate(object)

TypeError: value is undefined 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;
};

$httpBackend .whenGet is not a function in Angular

I am trying to make a dummy service to get data in Angular, I am using ngMockE2E, and my code for the Mock looks like this:
(function () {
"use strict"
var app = angular
.module("productResourceMock", ["ngMockE2E"]);
app.run(function ($httpBackend) {
var products = [
{
"productId": 1,
"productName": "mobile1",
"productCode": "heh4",
"releaseDate": "May 21, 2013",
"description": "very nice mobile",
"cost": 200,
"price": 300,
"category": "Electronics",
"tags": ["mobile", "electronic"],
"imageUrl": "images/img1.jpg"
},
{
"productId": 2,
"productName": "mobile2",
"productCode": "heh4",
"releaseDate": "May 21, 2012",
"description": "not a nice mobile",
"cost": 100,
"price": 500,
"category": "Electronics",
"tags": ["mobile", "Electronic"],
"imageUrl": "images/img2.jpg"
}];
var productUrl = "/api/products";
$httpBackend.whenGet(productUrl).respond(products);
});
}());
I have defined my controller, and inside it, it has this code:
(function () {
"use strict"
angular
.module("productManagement")
.controller("ProductListCtrl",
["productResource",
ProductListCtrl]);
function ProductListCtrl(productResource) {
var vm = this;
productResource.query(function(data){
vm.products = data;
});
}
}());
And for my service that sends the REST requests, I have this code:
(function () {
"use strict"
angular
.module("common.services")
.factory("productResource",
["$resource", productResource]);
function productResource($resource) {
return $resource("/api/products/:productId");
}
}());
am still getting this error: Uncaught TypeError: $httpBackend.whenGet is not a function.
Any help is appreciated, or any clarification needed, please let me know.
Answer is simple: replace whenGet with whenGET
Be careful to write the http verb all in uppercase.
See ngMock documentation

Laravel sort array by created_at

I need to sort my json array in chronological order by it's created_at timestamps.
[{
"id": 1,
"message": "hello",
"company_id": 7,
"investor_id": 35,
"match_id": 2,
"created_at": "2015-07-01 12:56:34",
"updated_at": "2015-07-01 12:56:34"
}, {
"id": 2,
"message": "helloWorld",
"company_id": 7,
"investor_id": 35,
"match_id": 2,
"created_at": "2015-07-01 12:56:53",
"updated_at": "2015-07-01 12:56:53"
}, {
"id": 3,
"message": "sup",
"company_id": 7,
"investor_id": 35,
"match_id": 2,
"created_at": "2015-07-01 13:12:53",
"updated_at": "2015-07-01 13:12:53"
}, {
"id": 4,
"message": "sup",
"company_id": 7,
"investor_id": 35,
"match_id": 2,
"created_at": "2015-07-01 13:13:04",
"updated_at": "2015-07-01 13:13:04"
}, {
"id": 5,
"message": "sup",
"company_id": 7,
"investor_id": 35,
"match_id": 2,
"created_at": "2015-07-01 15:06:39",
"updated_at": "2015-07-01 15:06:39"
}, {
"id": 1,
"message": "yo yo ",
"investor_id": 35,
"company_id": 7,
"match_id": 2,
"created_at": "2015-07-01 22:09:36",
"updated_at": "-0001-11-30 00:00:00"
}, {
"id": 2,
"message": "sup nigga",
"investor_id": 35,
"company_id": 7,
"match_id": 2,
"created_at": "2015-07-01 14:00:00",
"updated_at": "-0001-11-30 00:00:00"
}]
Can anyone teach me how do i have tried many solutions in stackoverflow . Many of them says array cannot be used with "sortBy" .
This is part of my code :
$companyMessage = Company_Message::where('match_id','=',$match_id);
$investorMessage = Investor_Message::where('match_id','=',$match_id);
$message = array();
if($companyMessage->count()>0 || $investorMessage->count() > 0){
if($lastActivityDate == null ){
//load all messages before
if($companyMessage !=null){
foreach ($companyMessage->get() as $cm) {
array_push($message,$cm);
}
}
if($investorMessage !=null){
foreach($investorMessage->get() as $im){
array_push($message,$im);
}
}
return $message ;
}
I think you can do this using use a laravel database collection api instead of array and add item to collection and use sortBy method on collection,
$col = new \Illuminate\Database\Eloquent\Collection();
if ($companyMessage != null) {
foreach($companyMessage - > get() as $cm) {
$col->add($cm);
}
}
if ($investorMessage != null) {
foreach($investorMessage - > get() as $im) {
$col->add($im);
}
}
$col = $col->sortBy('created_at');
//return the json
return Response::json($jsonArr->toArray());
--- OR ----
Try this but i didn't tested it. If this works then this would be the best way to do this.
$companyMessage = Company_Message::where('match_id','=',$match_id);
$investorMessage = Investor_Message::where('match_id','=',$match_id);
//$companyMessage & $investorMessage both are laravel database collection,
// so you can use merge method on collection to merge these two collections.
$allResults = $companyMessage->merge($investorMessage);
//use laravel collection sort method to sort the collection by created_at
$allResults = $allResults->sortBy('created_at');
//return the json
return Response::json($allResults->toArray());
if($companyMessage !=null){
foreach ($companyMessage->get() as $cm) {
array_push($message,$cm);
}
}
if($investorMessage !=null){
foreach($investorMessage->get() as $im){
array_push($message,$im);
}
}
$message = array_values(array_sort($message, function ($value) {
return $value['created_at'];
}));
Hey man , i found a better solution to sort my array. The answer can be found at laravel docs
http://laravel.com/docs/5.1/helpers#method-array-sort

Resources