Present information from JSON in two pages - javascript

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
}
};
})
};

Related

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

Pass $scope.model from directive to controller (Angularjs)

I have checked all the other posts and trust me, this is not a duplicate. Hope someone can help me. Here is the code.
HTML Code- When user clicks on Report, buildData gets executed. multiselect directive name is mu-ls.
<button ng-click="buildData(selected_items)">Report</button>
<div>Universe:</div>
<div><mu-ls pre-selected="member.roles" model="selected_items" options="roles"></muls></div>
Directive Code- The directive name is muLs. User can select multiple options using this directive. The $scope.model gives the array of ids which user selected.
angular.module('Select').directive('muLs', function () {
return {
restrict: 'E',
scope: {
model: '=',
options: '=',
pre_selected: '=preSelected'
},
template: "<div data-ng-class='{open: open}'>" +
"<button data-ng-click='open=!open;openDropdown()'>Select...</button>" +
"<ul aria-labelledby='dropdownMenu'>" +
"<li data-ng-repeat='option in options'> <a data-ng-click='setSelectedItem()'>{{option.name}}<span data-ng-class='isChecked(option.id)'></span></a></li>" +
"</ul>" +
"</div>",
controller: function ($scope) {
$scope.openDropdown = function () {
$scope.selected_items = [];
for (var i = 0; i < $scope.pre_selected.length; i++) {
$scope.selected_items.push($scope.pre_selected[i].id);
}
};
$scope.setSelectedItem = function () {
var id = this.option.id;
if (_.contains($scope.model, id)) {
$scope.model = _.without($scope.model, id);
} else {
$scope.model.push(id);
}
console.log($scope.model);
return false;
};
$scope.isChecked = function (id) {
if (_.contains($scope.model, id)) {
return 'glyphicon glyphicon-ok pull-right';
}
return false;
};
}
}
});
Controller Code- This should show the list of selected items listed above in the controller side. It shows undefined at the moment.
'use strict'
var Modd= angular.module('Select', []);
Modd.controller('SelectController', function ($scope, $timeout, $rootScope) {
$scope.roles = [
{ "id": 1, "name": "USA" },
{ "id": 2, "name": "France" },
{ "id": 3, "name": "Russia" }
];
$scope.member = { roles: [] };
$scope.selected_items = [];
$scope.buildData = function (selected_items) {
console.log("This is", $scope.model);
}
});
QUESTION- How can i use this directive value $scope.model in the controller side ??? Please suggest guys !!!
I tried $scope.selected_items first. It gives a list of selected items only once. Once i click Report button, it will give the list. If i again start clicking and deselecting list items, it would still show the previous values. not the current ones.
$scope.model continues to show the latest values selected.
You are passing selected_items to your directive so it will contain the value of model in your controller.
$scope.buildData = function () {
console.log("This is", $scope.selected_items);
}
model is two-way bound. So if you assign a $scope variable from your controller to the module attribute, it will be updated when the selected value changes.
Therefore you can console.log($scope.selected_items);

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.

Hard time using JS object in ng-repeat

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": []
}
}

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