AngularJS module app dependency - arrays

I have declared twp app modules in my app.js file-"requestDashboard" and "newRequestDashboard"..."newRequestDashboard" is dependent upon "requestDashboard"(I have an array of objects that I'd like to display. Both of the apps have a different controller assigned to them and the array is stored in "requestDashboard". I maybe trying to overcomplicate this but I cannot for some reason display any of the objects. Code below:
app.js:
angular.module( 'requestDashboard', ['ngRoute', 'ui.bootstrap']);
angular.module( 'newRequestDashboard', ['ngRoute', 'ui.bootstrap', 'requestDashboard']);
Controller in "requestDashboard"
angular.module("requestDashboard")
.controller( 'requestDashboardCtrl', function ($scope) {
//Dummy Data for user requests
$scope.requests = [
{
type: "meeting1",
meetingName: "Radiology San Diego",
location:"Sheraton Ballroom 5S",
subitems: [
{
name: "ESCALATED",
desc: "Power strips at every table",
priority:"1",
planner:"Jessica Q. Planner",
time:"02/15/15 at 8:15 AM",
quantity:"3; one power strip at ever table"
},
{
name: "OPEN",
desc: "Extra table for 3",
priority:"3",
planner:"Jessica Q. Planner"
},
{
name: "ACKNOWLEDGED",
desc: "Projector for meeting",
priority:"2",
planner:"Jessica Q. Planner"
},
{
name: "CLOSED",
desc: "book exta room for 2 guests",
priority:"5",
planner:"Jessica Q. Planner"
},
{
name: "CANCELLED",
desc: "extra chairs",
priority:"1",
planner:"Jessica Q. Planner"
}
]
},
{
type: "meeting2",
meetingName: "California Almond Growers",
location:"Sheraton FL14",
subitems: [
{
name: "ESCALATED",
desc: "need some more almonds",
priority:"1",
planner:"Jessica Q. Planner"
},
{
name: "OPEN",
desc: "extra pamphlets",
priority:"4",
planner:"Jessica Q. Planner"
},
{
name: "ACKNOWLEDGED",
desc: "Power supply",
priority:"2",
planner:"Jessica Q. Planner"
}
]
},
{
type: "meeting3",
meetingName: "Association of Amateur Archaeologists",
location:"Ansley 1- FL14",
subitems: [
{
name: "ESCALATED",
desc: "need some more experience",
priority:"1",
planner:"Jessica Q. Planner"
},
{
name: "OPEN",
desc: "need dinosaurs",
priority:"3",
planner:"Jessica Q. Planner"
}
]
}
];
});

It is very common to have many apps in your application. But you should take a different approach to this. In your solution you are declaring dependency on all your app. Which will conflict if your application gets bigger. What you should so is something like this.
// declare your app without any dependency
(function() {
var requestDashboard= angular.module( 'requestDashboard',[]);
}());
(function() {
var newRequestDashboard= angular.module( 'newRequestDashboard',[]);
}());
// inject all your dependency here
var mainApp = angular.module( 'mainApp ', ['requestDashboard','newRequestDashboard','ngRoute', 'ui.bootstrap']);
About your question, Why don't you use Services? and services can be consumed in controller and then you can display back to your view.
Hope this helps

Related

NextJs / React: Organizing Array

I'm having issues understanding how to best manipulate an array to get the data I want. From the research I've done, there's multiple ways, but I'm unclear on which is most optimized.
I want to display a simple list, with the items broken down by country, then state, then organized alphabetically by city. The array is formatted as follows:
[
{
id: 1,
name: "Place 1",
state: "Florida",
city: "Boca Raton",
country: "US",
},
{
id: 2,
name: "Place 2",
state: "Florida",
city: "Daytona Beach",
country: "US",
},
{
id: 3,
name: "Place 3",
state: "Kansas",
city: "Lenexa",
country: "US",
},
{
id: 4,
name: "Place 4",
state: "Harju",
city: "Tallinn",
country: "EE",
},
]
An example of the desired outcome is:
US
Florida
Place 1
Place 2
Kansas
Place 3
EE
Harju
Place 4
I see a lot of people saying to utilize ES6 for this, but I'm not sure the best way to approach it. Manipulate the original array response? Is there some way I can loop through them?
Here's an approach that only requires a single loop.
const data = [];
let result = {};
data.forEach(({ name, state, country }) => {
if (!result[country]) {
result[country] = {};
}
if (!result[country][state]) {
result[country][state] = [name];
}
else {
result[country] = {
...result[country],
[state]: [
...result[country][state],
name
]
};
}
});
console.log(result);
Output
{
US: { Florida: [ 'Place 1', 'Place 2' ], Kansas: [ 'Place 3' ] },
EE: { Harju: [ 'Place 4' ] }
}
I'm sure the if-else part can be removed by using spread operator and operator chaining, but I wasn't able to figure that out.
If your environment supports operator chaining, here's a smaller solution
const data = [];
let result = {};
data.forEach(({ name, state, country }) => {
result[country] = {
...result[country],
[state]: [
...(result?.[country]?.[state] || []),
name
]
};
});
console.log(result);

How to create sap.m.ComboBox without the strange 'is not a function' error?

I've been playing around with SapUI5 for a while and now I'm facing another issue, which is totally confusing me.
My goal: To add a ComboBox to an oTable.
What I tried: I decided to do the 'separation of concerns', in order to investigate it better, so I 'extracted' the ComboBox code from the table and am testing it on its own like this:
var cbWizardTypes = [
{
Code: "0",
Name: "Name0",
AdditionalText: "Additional0"
},
{
Code: "1",
Name: "Name1",
AdditionalText: "Additional1"
},
{
Code: "2",
Name: "Name2",
AdditionalText: "Additional2"
},
];
// now the template to use when showing the items
var cbWizardTypesTemplate = new sap.ui.core.ListItem({
key: "{Code}",
text: "{Name}",
additionalText: "{AdditionalText}"
});
// now let's create it and place it
var cbWizardType = new sap.m.ComboBox({
items: {
path: cbWizardTypes,
template: cbWizardTypesTemplate
},
showSecondaryValues: true
});
cbWizardType.placeAt(containerID, 'only');
Now, this is giving me this error in the console:
Additionally, I tried not to use a template, just to see what happens
var cbWizardType = new sap.m.ComboBox({
//items: {
// path: cbWizardTypes,
// template: cbWizardTypesTemplate
//},
items: cbWizardTypes,
showSecondaryValues: true
});
In this case, there are no errors in the Chrome Developer Tools - Console. I get a ComboBox with 3 items, but they are all blank.
Now, I will, at least, try to investigate further, although library-preload.js had been minified, so it will be really hard and time-consuming to navigate through all those 'd'-s, 'p'-s, 'j'-s, etc., I guess.
As always, I will appreciate any help. Thank you!
The problem lies with the binding path that you assign to the ComboBox. The binding should be a string & not an array. You will have to store the data in a model & bind it then to your control.
The code below should work
var cbWizardTypes = [
{
Code: "0",
Name: "Name0",
AdditionalText: "Additional0"
},
{
Code: "1",
Name: "Name1",
AdditionalText: "Additional1"
},
{
Code: "2",
Name: "Name2",
AdditionalText: "Additional2"
},
];
var oModel = new sap.ui.model.json.JSONModel({ items: cbWizardTypes});
// now the template to use when showing the items
var cbWizardTypesTemplate = new sap.ui.core.ListItem({
key: "{Code}",
text: "{Name}",
additionalText: "{AdditionalText}"
});
// now let's create it and place it
var cbWizardType = new sap.m.ComboBox({
items: {
path: "/items",
template: cbWizardTypesTemplate
},
showSecondaryValues: true
});
cbWizardType.setModel(oModel);
cbWizardType.placeAt(containerID, 'only');

Error in routing with id parameter, link works but displays no data

I am having an issue with retrieving the stored data (within MongoDB) by way of an :id parameter. The link works and takes me to the specified url (./contests/1), but the data doesn't show up. When querying within the mongo CMD with (db.contests.find( {id:1} )) the correct object's data is displayed correctly.
route/contest.js
router.route("/contests/:id")
.get(function(req, res, next) {
Contest.findOne({id: req.params.id}, function(err, contest) {
if(err) {
res.send(err);
}
res.json(contest);
});
service/contestService.js
app.factory("contestService", ["$http", "$resource",
function($http, $resource)
{
var o = {
contests: []
};
function getAll() {
return $http.get("/contests").then(function(res) {
angular.copy(res.data, o.contests);
});
}
function get(id) {
return $resource('/contests/:id');
}
o.getAll = getAll;
o.get = get;
return o;
}]);
})();
controller/contestController.js
var app = angular.module("sportsApp.controllers.contest,["ui.router"]);
app.config(["$stateProvider", function($stateProvider) {
$stateProvider.state("contest", {
parent: "root",
url: "/contests/:id",
views: {
"container#": {
templateUrl: "partials/contests",
controller: "ContestController"
}
}
});
}
]);
app.controller("ContestController", ["$scope","contestService", "$stateParams", function($scope, contestService, $stateParams) {
var contest_id = $stateParams.id;
$scope.contest = contestService.get({id: contest_id});
}]);
})();
Contest Schema
var mongoose = require("mongoose");
var ContestSchema = new mongoose.Schema(
{
id: Number,
tags: String,
matchups: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Matchup"
}],
usersWhoJoined: [{
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}]
});
mongoose.model("Contest", ContestSchema);
Any assistance or advice would be much appreciated due to the fact that I am learning as I go with the MEAN stack and have little to no experience with it.
I am looking to display the specific contest's matchups in which displays two teams and other variables. This is my json file that I mongoimported in order to create the object of the contests collection within MongoDB:
{
"id": 1,
"tags": "NBA",
"matchups": [{
"matchupId": 1,
"selectedTeam": "",
"matchupWinner": "Atlanta",
"nbaTeams": [{
"team": "Portland",
"logo": "stylesheets/nbalogos/Portland-Trail-Blazers-Logo.png"
}, {
"team": "Atlanta",
"logo": "stylesheets/nbalogos/atl-hawks.png"
}]
}, {
"matchupId": 2,
"selectedTeam": "",
"matchupWinner": "Dallas",
"nbaTeams": [{
"team": "Dallas",
"logo": "stylesheets/nbalogos/Dallas-Mavericks.png"
}, {
"team": "Detroit",
"logo": "stylesheets/nbalogos/DET.png"
}]
}, {
"matchupId": 3,
"selectedTeam": "",
"matchupWinner": "Golden State",
"nbaTeams": [{
"team": "Golden State",
"logo": "stylesheets/nbalogos/GSW.png"
}, {
"team": "Memphis",
"logo": "stylesheets/nbalogos/Memphis-Grizzlies.png"
}]
}, {
"matchupId": 4,
"selectedTeam": "",
"matchupWinner": "Oklahoma City",
"nbaTeams": [{
"team": "Oklahoma City",
"logo": "stylesheets/nbalogos/OKC-Thunder.png"
}, {
"team": "Pheonix",
"logo": "stylesheets/nbalogos/Pheonix-Suns.jpg"
}]
}, {
"matchupId": 5,
"selectedTeam": "",
"matchupWinner": "Utah",
"nbaTeams": [{
"team": "Sacremento",
"logo": "stylesheets/nbalogos/Sacremento-Kings.jpg"
}, {
"team": "Utah",
"logo": "stylesheets/nbalogos/Utah-Jazz.jpg"
}]
}]
}
I want to create each contest in this format.
I have no idea what relevance the actual data has to this issue, so let's start with $scope.contest, since there seems to be a problem with the way you're accessing data.
// ContestController
$scope.contest = contestService.get({id: contest_id});
OK, so you're calling the contestService.get method with an object, let's say it's {id: 2}. Let's look at that method and call it with that object.
// contestService
function get(id) {
return $resource('/contests/' + id);
}
If using our dummy data, if you call get({id: 2}), you now have an Angular resource at the URL /contests/[object Object] because your object gets converted into a string. Your method would work if called using the value at the id property of that object, like:
// ContestController
$scope.contest = contestService.get(contest_id);

Error: ng:areq - controllers in different files

I'm trying to separate every controller in my angular app, but I have this error:
23:51:38.389 "Error: [ng:areq] http://errors.angularjs.org/1.5.0-rc.0/ng/areq?p0=skillsController&p1=not%20a%20function%2C%20got%20undefined
P/<#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:6:421
sb#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:22:41
Ta#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:22:128
af/this.$get</<#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:84:42
B#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:62:118
v#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:63:115
Vf/<#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:72:397
e/<#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:123:217
pf/this.$get</m.prototype.$eval#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:137:442
pf/this.$get</m.prototype.$digest#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:135:33
pf/this.$get</m.prototype.$apply#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:138:234
g#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:91:372
t#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:95:492
ag/</v.onload#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:97:31
"1 angular.min.js:111:399
e/<() angular.min.js:111
cf/this.$get</<() angular.min.js:84
e/<() angular.min.js:123
pf/this.$get</m.prototype.$eval() angular.min.js:137
pf/this.$get</m.prototype.$digest() angular.min.js:135
pf/this.$get</m.prototype.$apply() angular.min.js:138
g() angular.min.js:91
t() angular.min.js:95
ag/</v.onload() angular.min.js:97
pkApp.js:
angular.module('pkApp', ['Controllers']).value("version", "1.160110");
controllersModule.js:
angular.module('Controllers', []);
skillsController.js:
angular.module('Controllers', [])
.controller('skillsController', ['$scope', function($scope){
$scope.skills = [
"html",
"css",
"js",
"jquery",
"angularjs",
"php",
"mysql",
"joomla"
];
}]);
portfolioController.js:
angular.module('Controllers', [])
.controller('portfolioController', ['$scope', function($scope) {
$scope.sites = [{
name: "Site1",
href: "http://www.site1.pl",
img: "1"
}, {
name: "Site 2",
href: "http://www.site2.pl",
img: "2"
}, {
name: "Site 3",
href: "http://www.site3.pl",
img: "3"
}];
}]);
It looks like angular see new module and only first controller that was to it, next is treat as function?
Thank you in advance.
A simple Solution could be:
Define a variable with your module in pkApp.js
var app = angular.module('pkApp', []);
You can delete the controllersModule.js
Create your Controllers as follows:
app.controller('skillsController', ['$scope', function($scope){
$scope.skills = [
"html",
"css",
"js",
"jquery",
"angularjs",
"php",
"mysql",
"joomla"
];
}]);
Same thing with your portfolio controller. It doesn't matter how many files you like to use for your controllers.
See also: https://docs.angularjs.org/guide/controller
Hope, that helps...

Angular select ngChange get the parent json object key not the value

I've created a hypothetical example; since i can't share my real example with you all. So forgive my hasty json file i created.
To the problem. Say i have a select populated like so using a json file which contains an array of (US State) objects:
State.json
{ "states":
[
{
code: "AL",
name: "Alabama"
},
{
code: "AK",
name: "Alaska"
},
{
code: "AS",
name: "American Samoa"
},
{
code: "AZ",
name: "Arizona"
},
{
code: "AR",
name: "Arkansas"
},
{
code: "CA",
name: "California"
},
{
code: "CO",
name: "Colorado"
},
{
code: "CT",
name: "Connecticut"
},
... etc...
]}
I pull in the json file and set it to a scope item like so:
main-controller.js
app.controller('MainCtrl', function ('$scope') {
$scope.states = [
{ code: "AL": name: "Alabama" },
//etc
];
$scope.selectStateChange = function (stateCode) {
console.log(stateCode);
}
});
index.html
Here's my select:
<select ng-model="selectedState" ng-change="selectStateChange(selectedState)">
<option ng-repeat="state in states">{{state.name}}</option>
</select>
My Problem
How does one get the actual state code to be passed into function selectStateChange on my ng-change?
You should try using ng-options instead of a ng-repeat on options.
This way your model will be up to date and it will be quite convenient to access the selected object.
It should looks like this in your case :
<select ng-model="selectedState" ng-options="state.name for state in states" ng-change="selectStateChange()">
</select>
and your JS should display your object:
app.controller('MainCtrl', function ('$scope') {
$scope.states = { "AL": "Alabama", //etc }
$scope.selectedState = null;
$scope.selectStateChange = function () {
console.log(selectedState);
}
});
This way, selectedState is equal to {
code: "AL",
name: "Alabama"
}
What get's logged into the console by console.log(stateCode);?
Did you try
$scope.selectStateChange = function (selectedState) {
console.log(selectedState.code);
}

Resources