Hard time using JS object in ng-repeat - javascript

I have a strangely structured object which I am trying to convert to an array so that I am able to use filters with ng-repeat.
Here is an example object:
var sysData = {
"walkerduct": {
"id": 0,
"uri": "walkerduct",
"name": "Walkerduct",
"imageS": "img/callcenter.jpg",
"imageL": "img/callcenter.jpg",
"copy": "Walkerduct info",
"relatedSys": [],
"relatedApp": []
}
}
My controller where I attempt to convert it to an array,
inFloorControllers.controller('ApplCtrl', ['$scope', '$routeParams',
function ($scope, $routeParams) {
//alert("OtherCtrl hit");
$scope.appData = appData;
$scope.sysData = sysData;
$scope.title = appData.title;
$scope.sysArr = [];
var hasData = true;
var idx = 0;
while (hasData) {
var data = sysData[idx];
alert("yo");
if (data) {
$scope.sysArr.push(data);
idx++;
}
else {
hasData = false;
}
}
for (i = 0; i < $scope.sysArr.length; i++) {
alert($scope.sysArr[i]);
}
}
]);
And finally my HTML,
<div ng-repeat="sys in sysArr | limitTo:3">
<a href=#/systems/{{sys.uri}}>{{sys.name}}</a>
</div>
I'm not seeing what I am doing wrong... it doesn't even hit if(data)... thanks.

Just use Object.keys combined with Array.map, like this:
inFloorControllers.controller('ApplCtrl', ['$scope', '$routeParams',
function ($scope, $routeParams) {
$scope.appData = appData;
$scope.sysData = sysData;
$scope.title = appData.title;
$scope.sysArr = Object.keys($scope.sysData).map(function(key){
return $scope.sysData[key];
});
}
]);
If you need support for IE8 you will need the polyfill for the map function.

That is not a valid json. remove the last comma
{
"walkerduct": {
"id": 0,
"uri": "walkerduct",
"name": "Walkerduct",
"imageS": "img/callcenter.jpg",
"imageL": "img/callcenter.jpg",
"copy": "Walkerduct info",
"relatedSys": [],
"relatedApp": []
}
}

Related

angular Chart data-pushing from another javascript

I have an array in data_controller.js and i wanted my main.js, where I edit my angular chart there, to be able to fetch the array. Any specific way on doing this?
Data_Controller.js:
/*global angular*/
var app = angular.module('statisticsApp', [chart.js]).controller('myCtrl',
function ($scope, $http) {
"use strict";
return $http({
method : "POST",
url : "GatewayAPI.php",
}).then(function mySuccess(response) {
$scope.records = response.data;
var mydata,myJSON,myresult,myjava, myobj;
var i;
var Result;
var chartResultTemp = [];
var chartResultph = [];
var chartResultHum = [];
var resultType = [];
for(i=0; i<72;i++)
{
//storing data
mydata = $scope.records.data[i];
//retrieving data
myobj = mydata.data.substring(3,4);
resultType = mydata.data.substring(3, 4);
if(resultType === "A") {
chartResultTemp.push([mydata.data.substring(6,9)]);
} else if (resultType ==="B") {
chartResultph.push([mydata.data.substring(6, 9)]);
} else {
chartResultHum.push([mydata.data.substring(6, 9)]);
};
$scope.test=Result; //change to array
$scope.test2=chartResultTemp;
$scope.test3 = resultType;
$scope.test4 = chartResultph;
$scope.test5 = chartResultHum;
console.log(Result);
console.log(resultType);
}
$scope.gotTemp = false;
$scope.gotHumidity = false;
$scope.getSoilMoisture = false;
});
});
main.js:
var app = angular.module("statisticsApp", ["chart.js"]);
app.controller("LineCtrl", function ($scope) {
"use strict";
$scope.labels = ["0200", "0400", "0600", "0800", "1000", "1200", "1400",
"1600", "1800", "2000", "2200", "0000"];
$scope.series = ['Temperature (°C)'];
$scope.data = [
[26.5, 26.8, 26.3, 25.8, 29.4, 30.2, 31.5, 31.0, 28.4, 27.6, 26.3, 25.7]
];
$scope.onClick = function (points, evt) {
console.log(points, evt);
};
});
I have tried putting the chart function from main,js into data_controller.js and wrote $scope.data.push([mydata.data.substring(6,9)]) but that did nothing.
How do I call the function in data_controller.js and use the array in my $scope.data = [] in main.js?
If you want to reuse that method for retrieving data, it would be best to decouple it into a service. Then, you can use it all of your controllers.
Please note that code below is just to showcase the implementation, it might not work straight away if you just copy-paste it.
//statisticsSvc.js
angular.module('statisticsApp').service('statisticsService',['$http' function($http){
var data = [];
return {
getStatistics: function(){
return $http({
method : "POST",
url : "GatewayAPI.php",
})
.then(function(response){
var mydata,myJSON,myresult,myjava, myobj;
var i;
var Result;
var chartResultTemp = [];
var chartResultph = [];
var chartResultHum = [];
var resultType = [];
for(i=0; i<72;i++)
{
//storing data
mydata = response.data.data[i];
//retrieving data
myobj = mydata.data.substring(3,4);
resultType = mydata.data.substring(3, 4);
if(resultType === "A") {
chartResultTemp.push([mydata.data.substring(6,9)]);
} else if (resultType ==="B") {
chartResultph.push([mydata.data.substring(6, 9)]);
} else {
chartResultHum.push([mydata.data.substring(6, 9)]);
};
return {
records: response.data.data,
Result: Result,
chartResultTemp: chartResultTemp,
resultType: resultType,
chartResultph: chartResultph,
chartResultHum: chartResultHum
};
}
})
.catch(function(error){
console.log(error);
return error;
})
},
setData: function(a){ data = a;},
getData: function(){ return data;}
};
}]);
Then, you can use this service in your controllers:
//myCtrl
var app = angular.module('statisticsApp', [chart.js]).controller('myCtrl',
function ($scope, $http,statisticsService) {
//your call to service
statisticsService.getStatistics().then(function(response){
$scope.records = response.records;
$scope.test = response.Result;
$scope.test2 = response.chartResultTemp;
$scope.test3 = response. resultType;
}).error(function(error){
console.log(error);
});
//get data
$scope.data = statisticsService.getData();
});
//LineCtrl
var app = angular.module("statisticsApp", ["chart.js"]);
app.controller("LineCtrl", function ($scope, statisticsService) {
"use strict";
$scope.labels = ["0200", "0400", "0600", "0800", "1000", "1200", "1400",
"1600", "1800", "2000", "2200", "0000"];
$scope.series = ['Temperature (°C)'];
$scope.data = [
[26.5, 26.8, 26.3, 25.8, 29.4, 30.2, 31.5, 31.0, 28.4, 27.6, 26.3, 25.7]
];
//set data
statisticsService.setData($scope.data);
$scope.onClick = function (points, evt) {
console.log(points, evt);
};
});

Making a checkbox using AngularJS

I'm trying to make a checkBox using AngularJS, I found this code :
http://jsfiddle.net/t7kr8/211/
and following its steps my code was :
JS File:
'use strict';
var app = angular.module('myApp.Carto', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/Carto', {
templateUrl: 'Carto/carto.html',
controller: 'CartoCtrl'
});
}])
app.controller('CartoCtrl', function($scope) {
$scope.array = [];
$scope.array_ = angular.copy($scope.array);
$scope.list = [{
"id": 1,
"value": "apple",
}, {
"id": 3,
"value": "orange",
}, {
"id": 5,
"value": "pear"
}];
});
app.directive("checkboxGroup", function() {
return {
restrict: "A",
link: function(scope, elem) {
// Determine initial checked boxes
if (scope.array.indexOf(scope.item.id) !== -1) {
elem[0].checked = true;
}
// Update array on click
elem.bind('click', function() {
var index = scope.array.indexOf(scope.item.id);
// Add if checked
if (elem[0].checked) {
if (index === -1) scope.array.push(scope.item.id);
}
// Remove if unchecked
else {
if (index !== -1) scope.array.splice(index, 1);
}
// Sort and update DOM display
scope.$apply(scope.array.sort(function(a, b) {
return a - b;
}));
});
}
};
});
However, when I run the code in the browser the checkbox appears but I can't chack the boxes, does that mean the directive doesn't work ?
I could'nt figure out what was going wrong because I practically just copied the code in the link provided above , can you please help me how to fix this ?
Thank you in advance
PS: I think it's due to materialize but I still don't know how or how to fix it
I think you've made a mistake with the module name.
I recreated your sample code and it works perfectly fine: JSFiddle
Code:
var myApp = angular.module('myApp', []);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.array = [];
$scope.array_ = angular.copy($scope.array);
$scope.list = [{
"id": 1,
"value": "apple",
}, {
"id": 3,
"value": "orange",
}, {
"id": 5,
"value": "pear"
}];
}
myApp.directive("checkboxGroup", function() {
return {
restrict: "A",
link: function(scope, elem) {
// Determine initial checked boxes
if (scope.array.indexOf(scope.item.id) !== -1) {
elem[0].checked = true;
}
// Update array on click
elem.bind('click', function() {
var index = scope.array.indexOf(scope.item.id);
// Add if checked
if (elem[0].checked) {
if (index === -1) scope.array.push(scope.item.id);
}
// Remove if unchecked
else {
if (index !== -1) scope.array.splice(index, 1);
}
// Sort and update DOM display
scope.$apply(scope.array.sort(function(a, b) {
return a - b
}));
});
}
}
});
HTML:
<div ng-controller="MyCtrl">
<div ng-repeat="item in list">
<input type="checkbox" checkbox-group />
<label>{{item.value}}</label>
</div>
</div>
The error was due to the presence of both bootstrap and Materialize , apparently there is a conflict between the two and when I deleted bootstrap, it all worked well

Present information from JSON in two pages

I'm trying to create a webpage which reads json. I have a first page,index, that works just fine. I get correct information from json and print it out correct. But, I want to have a subpage, which have more details. To get this details.
I don't know how to take out the specific object from json and present the information on another page?
My code looks like this:
EXAMPLE JSON
{
"Name": "foo",
"array": [
1,
2,
3
],
"boolean": true,
"null": null,
"number": 123,
"object": {
"a": "b",
"c": "d",
"e": "f"
},
"string": "Hello World"
}
Lets say that i have 5 jsonobject like this. On my index-page i do ng-repeat to print them, for example, name and number. The name is a link to "more details"-page. More detail presents, for example the array.
ReadJson
var readJSON = function($scope, $interval, $http){
$http.get("./output/resultJSON.json").success(function(response) {
$scope.result = response;
})
ReadMoreDetails
var readDetails = function($scope, $routeParams){
};
ng-route
var application = angular.module("application", ['ngRoute']);
application.config(function($routeProvider){
$routeProvider
.when("/index.html", {
templateUrl: "index.html"
})
.when("/showTable", {
templateUrl: "templates/resultTable.html",
controller: "readJSON"
})
.when("/showMoreDetails/:id", {
template: "templates/moreDetails.html",
controller: "readDetails"
})
.otherwise({redirectTo:"/showTable"});
});
MyLink
<div class="link" ng-click="result.Name">{{result.Name}}</div>
You can do this,
var readDetails = function($scope, $routeParams){
$http.get("./output/resultJSON.json").success(function(response) {
$scope.result = response;
for (var i = 0; i < $scope.result.length; i++) {
if($scope.result[i].Name == $routeParams.id {
$scope.details = $scope.result[i].array
}
};
})
};

Adding an array of objects to an Angular scope object -- TypeError

I'm getting this error: "TypeError -- cannot set property 'select' of undefined" in the promise for a repository function.
The variable obj contains an array of objects.
.then(function (obj) {
// this works...
var abc = {};
abc.title = "hello";
abc.obj = obj;
// this doesn't work...
$scope.modelData = {};
$scope.title = "Import";
$scope.message = "Please select a Purchase Request"
$scope.select = obj; // <-- TypeError -- cannot set property 'select' of undefined'
It's raising the error during an angular function so I'm sure it's Angular that doesn't like it.
=== Edited to include more code.
Here's the relevant bits of my controller:
var app = ipoModule.controller("ipoController",
function ($scope, $compile, $window, $http, $q, $log, ipoRepository, $routeParams, limitToFilter, $modal, ngTableParams) {
$scope.ipoRepository = ipoRepository;
//... not-relevant stuff
$scope.PRList = ipoRepository.getMvpPRs($scope.POHeader.warehouseId)
.then(function (obj) {
var modelData = {};
modelData.title = "MVP Import";
modelData.message = "MVP Purchase Request ID";
modelData.select = obj;
$scope.modalData = modelData;
// then do more stuff but it breaks before that...
})
.catch(function (err) {
$scope.HandleErrorDoc('Search Error', err)
});
})
and here's some of my repository
ipoModule.factory('ipoRepository', function($resource, $http) {
var genericGet = function(params, URL) {
return $http.get(URL, {
params: params
}).then(function(res) {
if (res.data) {
return res.data;
} else {
return null;
}
});
};
return {
getSearchResults: function(txt, chk, myPO) {
return genericGet({
SearchText: txt,
excludeCompleted: chk,
MyPO: myPO
}, '/Search/GetSearchResults');
},
getMvpPRs: function(id) {
return genericGet({
id: id
}, '/MvpUtility/GetMvpPRs')
}
}
});
... and now the module ...
var ipoModule = angular.module('ipoModule', ['ngRoute', 'ngResource', 'ngGrid', 'ui.bootstrap', 'unsavedChanges', 'ngIdle', 'ngTable'])
.config(function($routeProvider, $locationProvider, unsavedWarningsConfigProvider) {
//$locationProvider.html5Mode(true);
unsavedWarningsConfigProvider.useTranslateService = false;
});
I came to the conclusion that Angular couldn't figure out how to handle an array of objects so I tried to create the object as a regular javascript variable first and then assign it to a scope variable ... and it worked.
I'll leave this unanswered though because there may be an "angular" way to do this which I am not aware of.
$scope.PRList = ipoRepository.getMvpPRs($scope.POHeader.warehouseId)
.then(function (obj) {
var modelData = {};
modelData.title = "MVP Import";
modelData.message = "MVP Purchase Request ID";
modelData.select = obj;
$scope.modalData = modelData;
and here's a sample of what is returned in my obj variable:
[
{
"prid": "0000",
"description": "PR0000 - j11-v1 test - youngm Jan 11"
},
{
"prid": "0001",
"description": "PR0001 - j11-v1 test - youngm Jan 11"
},
{
"prid": "0004",
"description": "PR0004 - j11-v1 test - j20-contractor Jan 20"
},
{
"prid": "0005",
"description": "PR0005 - tigerdirect - yeungm Mar 01"
}
]
I see modelData and modalData in your example.
I assume you wrote smth like
$scope.modelData = {};
$scope.modalData.select = [];
But it's impossible to say without full version of broken code.
Or, you miss $scope injection in first version of code.
Anyway, issue is not angular related.

Match the routeParam with the ID property and display the relevant object

I have a JSON file that looks like this:
[
{
"id":"112",
"title":"Title here",
"date":"1234567890"
}
{
"id":"113",
"title":"Title here",
"date":"1234567890"
}
...
]
I have two partials/views. A list view which lists all of the objects, and a detail page which is triggered by an "ng-click" which takes as a parameter the "id" property.
I have my routes working, and a detail partial.
I built a service to performe the request, and two controllers:
var chatServices = angular.module('itemServices', ['ngResource']);
chatServices.factory('Item',['$resource',
function($resource){
return $resource('data.json', {}, {
query: {method:'GET', params:{}, isArray:true}
});
}
]);
chatListApp.controller('ItemsController', ['$scope', 'Item', "$location",
function ($scope, Item, $location) {
$scope.items = Item.query();
$scope.detailPage = function (hash) {
$location.path(hash);
}
}]);
chatListApp.controller('DetailController', ['$scope', '$routeParams', 'Item',
function($scope, $routeParams, Item) {
$scope.data = Item.query();
$scope.itemID = $routeParams.itemID;
}
]);
So, I have a url like http://domain.foo/112, and I want it to show the first object of my JSON file (or the data array, if you prefer).
When I try {{data[0]}} in my view, I get the object, so how do I go about adding some logic and fetching the object with ID value equal to $scope.itemID (as in the routeParams?
You have the id, and you have the data, so you can loop over the data the get the item:
chatListApp.controller('DetailController', ['$scope', '$routeParams', 'Item',
function($scope, $routeParams, Item) {
$scope.itemID = $routeParams.itemID;
$scope.data = Item.query(function() {
for (var i = 0; i < $scope.data.length; i++) {
if ($scope.data[i].id === $scope.itemID) {
$scope.item = $scope.data[i];
break;
}
}
});
}
]);
then use item in your view.
Update: Use angular.forEach to replace for loop like this:
angular.forEach($scope.data, function(item) {
if (item.id === $scope.itemID) {
$scope.item = item;
}
});

Categories