I defined a JavaScript function using a custom service and I called this function using the service in my controller. This function uses two parameters: The first one is input which I am getting by hitting the below API and the second one is the value of the year which I'm getting using ng-model directive. When I am calling this function in my controller I am getting an error like type is not defined or id is not defined etc. Is it the right way to call a JavaScript function in the controller. Please suggest me.
$http.get("http://152.144.218.70:8080/USACrime/api/crimeMultiple?city=" +$scope.strCity + "&crime=" + $scope.type1 + "&model=" + model).success(function (result) {
$scope.prograssing = false;
console.log("manisha", $scope.strCity);
console.log("kanika", result);
$scope.output = result;
console.log("monga", $scope.output);
$scope.hex = hexafy.year_city($scope.output,$scope.type);
console.log("service", $scope.hex);
});
myapp.js
var app= angular.module("myApp",["ngRoute","leaflet-directive","pb.ds.components"]);
var geomarker = new L.FeatureGroup();
app.service('hexafy', function() {
this.year_city = function (input2,years) {
if(years.toLowerCase()=="all"){
years = "2012,2013,2014,2015,2016,2017,2018,2019";
}
var yrs = years.split(",");
output = {};
outerBoundary = {};
boundary = {};
boundary["boundaryId"] = input[0]["id"];
boundary["boundaryType"] = input[0]["type"];
boundary["boundaryRef"] = "C1";
outerBoundary["boundary"] = boundary;
output["boundaries"] =outerBoundary;
themes = [];
for(var i in input){
crimeTheme = {};
crimeThemeValue = {};
crimeThemeValue["boundaryRef"] = "C1";
result = [];
for(var j in input[i]["prediction"]){
dict = {};
if(yrs.indexOf(input[i]["prediction"][j]["year"])>-1){
dict["name"] = input[i]["prediction"][j]["year"]+" "+input[i]["crime"]+" Crime";
dict["description"] = input[i]["crime"]+" Crime for "+input[i]["prediction"][j]["year"];
dict["value"] = input[i]["prediction"][j]["count"];
dict["accuracy"] = input[i]["accuracy"];
result.push(dict);
}
}
crime = input[i]["crime"].toLowerCase()+"CrimeTheme";
crimeThemeValue["individualValueVariable"] = result;
console.log('crimeThemeValue["individualValueVariable"]',crimeThemeValue["individualValueVariable"]);
crimeTheme[crime] = crimeThemeValue;
themes.push(crimeTheme);
console.log("themes",JSON.stringify(themes));
}
output["themes"] = themes;
console.log(output);
return output;
};
});
});
1) .success and .error methods are deprecated and it is not good to go with it. Instead you'd better use .then(successCallback, errorCallback)
2) To use a service method the proper way is to it like this:
app.service('myService', function() {
var service = {
method:method
};
return service;
function method() {
//Logic
}
})
So in your case the way to go is:
app.service('hexafy', function () {
return {
years_city: function (input2, years) {
if (years.toLowerCase() == "all") {
years = "2012,2013,2014,2015,2016,2017,2018,2019";
}
var yrs = years.split(",");
output = {};
outerBoundary = {};
boundary = {};
boundary["boundaryId"] = input[0]["id"];
boundary["boundaryType"] = input[0]["type"];
boundary["boundaryRef"] = "C1";
outerBoundary["boundary"] = boundary;
output["boundaries"] = outerBoundary;
themes = [];
for (var i in input) {
crimeTheme = {};
crimeThemeValue = {};
crimeThemeValue["boundaryRef"] = "C1";
result = [];
for (var j in input[i]["prediction"]) {
dict = {};
if (yrs.indexOf(input[i]["prediction"][j]["year"]) > -1) {
dict["name"] = input[i]["prediction"][j]["year"] + " " + input[i]["crime"] +
" Crime";
dict["description"] = input[i]["crime"] + " Crime for " + input[i]["prediction"]
[j]["year"];
dict["value"] = input[i]["prediction"][j]["count"];
dict["accuracy"] = input[i]["accuracy"];
result.push(dict);
}
}
crime = input[i]["crime"].toLowerCase() + "CrimeTheme";
crimeThemeValue["individualValueVariable"] = result;
console.log('crimeThemeValue["individualValueVariable"]', crimeThemeValue[
"individualValueVariable"]);
crimeTheme[crime] = crimeThemeValue;
themes.push(crimeTheme);
console.log("themes", JSON.stringify(themes));
}
output["themes"] = themes;
console.log(output);
return output;
}
}
})
Related
Below is my code. if we use set timeout function we got all data but we not use we are not getting inspection data which is coming from my local db. i want use deferred and promises in my code. Thanks in advance.
function onclickToCall() {
this.$('.check-list > .check-list-box').each(function (i) {
var j = i + 1;
var answer_req = $(this).attr("data-isReq");
var checklist_guid = $(this).attr("data-guid");
var question_type = $(this).attr("data-type");
var yes_no = $("input:radio[name='radio_" + j + "']:checked").val();
var notes = $(this).find('#txtAreaNotes_' + j).val();
var attachment_url = $(this).find(".txtCameraImage").attr("data-path");
var appConfig = DriverConnectApp.State.get('config_settings');
var item = {};
item.checklist_guid = checklist_guid;
item.yes_no = yes_no;
item.attachment_url = attachment_url;
item.notes = notes;
if (question_type == 2) { // For Vehical visual inspection
var dataPromise = that.getInspectionData(checklist_guid);
dataPromise.done(function (response, vh_image) {
var inspectionItem = {};
inspectionItem.vh_url = vh_image;
inspectionItem.details = response;
item.vh_inspection = inspectionItem;
that.detailsArr.push(item);
});
} else {
item.vh_inspection = {};
that.detailsArr.push(item);
}
});
// after finish and push all data we need to call function here
test();
}
getInspectionData: function (checklist_guid) {
var that = this;
var deferred = $.Deferred();
that.dbchecklist.getVehicleInspectionlist(checklist_guid, function (data, res) {
var details = [];
if (data.length) {
var img = data[0].vh_image;
var arr = JSON.parse(data[0].vh_details);
for (var k = 0; k < arr.length; k++) {
var items = {};
items.number = arr[k].number;
items.notes = arr[k].notes;
items.attachment_url = arr[k].attachment_url;
details.push(items);
}
deferred.resolve(details, img);
} else {
deferred.resolve(details, img);
}
});
return deferred.promise();
}
i was tested to the IdentyfyTask.
But I could not get a response before the value addCallback.
i want to the pnu values.
But pnu vaule was alwayes undefined...
my code is follows.
function poiClick(){
agmap.addEvent("click", function(evt){
getPoi= krcgis.Function.PoiClick(agmap ,evt);
console.log("X === ",getPoi.x);
console.log("Y === ",getPoi.y);
console.log("PNU === ",getPoi.pnu);
});
}
PoiClick : function(map, evt) {
poiInfo = {};
poiInfo.x =evt.mapPoint.x;
poiInfo.y =evt.mapPoint.y;
var targetLayerId = 'LP_PA_CBND';
var url = map.Layers.getLayerInfo(targetLayerId).SVC_URL;
var map = map.getMap();
//파라미터 설정.
var idParams = new krcgis.core.tasks.IdentifyParameters();
idParams.geometry = evt.mapPoint;
idParams.mapExtent = map.extent;
idParams.returnGeometry = true;
idParams.tolerance = 0;
idParams.layerOption = krcgis.core.tasks.IdentifyParameters.LAYER_OPTION_ALL;
idParams.width = map.width;
idParams.height = map.height;
idTask = new krcgis.core.tasks.IdentyfyTask(url);
idTask
.execute(idParams)
.addCallback(function (response) {
if (response) {
poiInfo.pnu =response[0].value;
}
});
return poiInfo;
}
The results were as follows.
IdentifyTask returns a IdentifyResult object. so you code response[0].value will be undefined.
you should use something like response[0].feature.attributes.PNU
I wrote a script, which creates 3 objects. The constructor has a local variable mushroomsCount:
Mushroom = function(num) {
var mushroomsCount = 0;
this.id = num;
this.Create();
}
Mushroom.prototype.Create = function() {
this.mushroomsCount++;
}
Mushroom.prototype.Display = function() {
console.log('mushromms count total is: ' + Mushroom.mushroomsCount);
}
$(document).ready(function() {
var mushroom = [];
mushroom[0] = new Mushroom(0);
mushroom[1] = new Mushroom(1);
mushroom[2] = new Mushroom(2);
mushroom[2].Display(); // first way
Mushroom.Display(); // second way
});
after creating the objects, I try to display the number of the objects at Mushroom.prototype.Display(), but I'm getting undefined.
codepen
You can use a property on Mushroom itselft (like you already had, but not had accessed).
function Mushroom(num) {
this.id = num;
this.create();
}
Mushroom.mushroomCount = 0; // this is public!
Mushroom.prototype.create = function () {
Mushroom.mushroomCount++;
}
Mushroom.prototype.display = function () {
document.write('mushromms count total is: ' + Mushroom.mushroomCount + '<br>');
}
var mushroom = [];
mushroom[0] = new Mushroom(0);
mushroom[1] = new Mushroom(1);
mushroom[2] = new Mushroom(2);
mushroom[0].display();
mushroom[1].display();
mushroom[2].display();
Or use a closure with an IIFE:
var Mushroom = function () {
var mushroomCount = 0;
var f = function (num) {
this.id = num;
this.create();
};
f.prototype.create = function () { mushroomCount++; }
f.prototype.display = function () { document.write('mushromms count total is: ' + mushroomCount + '<br>'); }
return f;
}();
var mushroom = [new Mushroom(0), new Mushroom(1), new Mushroom(2)];
mushroom[0].display();
mushroom[1].display();
mushroom[2].display();
Simple count instances of Mushroom 'class':
function Mushroom(num) {
this.id = num;
Mushroom.count++;
}
Mushroom.count = 0;
Mushroom.prototype.Display = function () {
document.write('mushromms count total is: ' + Mushroom.count + '<br>');
}
var mushroom = [];
mushroom[0] = new Mushroom(0);
mushroom[1] = new Mushroom(1);
mushroom[2] = new Mushroom(2);
mushroom[2].Display();
I am trying to call the method getTitulo, getDuracion and getLink inside the cancion.js file but when i call the function it returns the following error: "listaCanciones_Lcl[i].getTitulo is not a function". I have searched in different websites but i didnt got lucky with finding an answer. Hopefully someone here can give me some help, i will gladly appreciate it!
//Logic.js file
var listaCanciones = [],
ejecuTitulo = '',
ejecuDuracion = '',
ejecuLink = '';
var btnGenerarLista = document.getElementById("addList").addEventListener("click", agregarCanc);
var btnAgregarLista = document.getElementById("gnrList").addEventListener("click", llenarTabla);
function agregarCanc (){
var nameSong = document.querySelector('#nameSong').value;
var duraSong = document.querySelector('#duraSong').value;
var linkSong = document.querySelector('#linkSong').value;
var objCancion = new Cancion(nameSong, duraSong, linkSong);
listaCanciones.push(objCancion);
var listaCancionesJson = JSON.stringify(listaCanciones);
localStorage.setItem('json_canciones', listaCancionesJson);
}
function llenarTabla (titulo){
var celdaTitulo = document.querySelector('#tituloList'),
celdaDuracion = document.querySelector('#duracionList'),
celdaLink = document.querySelector('#linkList'),
listaCanciones_Lcl = JSON.parse(localStorage.getItem('json_canciones'));
for(var i=0; i<listaCanciones_Lcl.length;i++){
// Acceder a lista canciones
I am getting an error in this line, where is says "getTitulo" is not a function but i dont really know why?
var nodoTextoTitulo = document.createTextNode(listaCanciones_Lcl[i].getTitulo()),
nodoTextoDuracion = document.createTextNode(listaCanciones_Lcl[i].getDuracion()),
nodoTextoLink = document.createTextNode(listaCanciones_Lcl[i].getLink());
// Create td
var elementoTdTitulo = document.createElement('td'),
elementoTdDuracion = document.createElement('td'),
elementoTdLink = document.createElement('td');
// Celda Id Append Child
elementoTdTitulo.appendChild(nodoTextoTitulo);
elementoTdDuracion.appendChild(nodoTextoDuracion);
elementoTdLink.appendChild(nodoTextoLink);
// Fila Append Child
celdaTitulo.appendChild(elementoTdTitulo);
celdaDuracion.appendChild(elementoTdDuracion);
celdaLink.appendChild(elementoTdLink);
}
}
//Cancion.js File
var Cancion = function(pTitulo, pDuracion, pLink){
var id = 0;
var titulo = pTitulo;
var duracion = pDuracion;
var link = pLink;
this.getId = function (){
return id;
};
this.setTitulo = function (pTitulo){
titulo = pTitulo;
};
this.getTitulo = function(){
return titulo;
};
this.setDuracion = function(pDuracion){
duracion = pDuracion;
};
this.getDuracion = function(){
return duracion;
};
this.setLink = function (pLink){
link = pLink;
};
this.getLink = function(){
return link;
};
};
First, make sure you are loading the Cancion.js file before the others in your HTML. Your problem is that when you parse the JSON back out of local storage, Cancion is not a known object, so getTitulo is undefined. You'll have to do listaCanciones_Lcl[i].titulo; instead.
And another change you'll need is to loosen the scope of your variables. The reason you need this.x = pX is because before JSON.stringify(new Cancion(1, 2, 3)) just returned "{}". With this code it returns "{"id":0,"titulo":1,"duracion":2,"link":3}", which I think is what you were after.
function Cancion(pTitulo, pDuracion, pLink){
this.id = 0;
this.titulo = pTitulo;
this.duracion = pDuracion;
this.link = pLink;
this.getId = function (){
return this.id;
};
this.setTitulo = function (pTitulo){
this.titulo = pTitulo;
};
this.getTitulo = function(){
return this.titulo;
};
this.setDuracion = function(pDuracion){
this.duracion = pDuracion;
};
this.getDuracion = function(){
return this.duracion;
};
this.setLink = function (pLink){
this.link = pLink;
};
this.getLink = function(){
return this.link;
};
};
var objWithFunction = {
name: 'Object with Function',
getName: function() { return this.name }
};
undefined
objWithFunction.getName() // --> "Object with Function"
var string = JSON.stringify(objWithFunction)
string // -=> "{"name":"Object with Function"}"
JSON is for data only..
Better you create a model, and fill it with data.. but this model has to exist in your application.. or you load the model parallel to your data..
function SomeThing() {};
SomeThing.prototype.getName = function() { return this.name };
var Thing1 = new SomeThing(JSON.parse("{name:'ThingOne'}"));
Thing1.getName(); // ThingOne
I'm new to Angular and my experience with Javascript is not very extensive. I am failing to show data in ngGrid using following code. What is the problem?
In essence. I am loading data from a web-service, performing a transform (pivot) on it and then I want to present it in a grid.
Please see the following
app.js -> starting poing
var konstruktApp= angular.module('konstruktApp',['ngGrid']);
dataService.js -> web service call
'use strict';
konstruktApp.service('DataService',function DataService($http){
var callHttp = function(){
delete $http.defaults.headers.common['X-Requested-With'];
return $http.get("http://83.250.197.214/konstrukt.service/Konstrukt.SL.DummyBudgetService.svc/GetDummyBudgetData/");
};
return {
getDummyData: callHttp
};
});
ngGridController.js -> where the logic resides...
$scope.getData = DataService.getDummyData;
$scope.gridOptions = {data:'result'};
var getData = function() {
$scope.getData().then(function (response) {
var res = pivotData(response.data);
$scope.result = res.data.PivotedRows;
$scope.columns = res.cols;
console.log('from the success handler at ' + new Date());
}, function (reason) {
console.log('failed: ');
console.log(reason);
});
};
..and here is the logic that "pivots" the data
var pivotData = function(data) {
var firstColumn = "Dim1";
var secondColumn = "Period";
var columns = [];
columns.push({
field: firstColumn,
enableCellEdit: false
});
var pivotedArray = {};
pivotedArray.PivotedRows = [];
var rowItems = [];
var rowArray = {};
var previusFirstColumnValue = -1;
var firstColumnValue = 1;
//for each row
for (var i = 0; i < data.Rows.length; i = i + 1) {
//firstColumnValue = $scope.dataCollection.Rows[i].FindCell.Cells[firstColumn].Value;
firstColumnValue = findCell(data.Rows[i].Cells, firstColumn).Value;
//var secondColumnValue = data.Rows[i].Cells[secondColumn].Value;
var secondColumnValue = findCell(data.Rows[i].Cells, secondColumn).Value;
//if first column value has changed, add new row
if (firstColumnValue != previusFirstColumnValue) {
if (i !== 0) {
for (var j = 0; j < rowItems.length; j = j + 1) {
rowArray[rowItems[j].name] = rowItems[j].value;
}
pivotedArray.PivotedRows.push( rowArray);
rowArray = {};
rowItems = [];
}
rowItems.push({
name: firstColumn,
//value: $scope.dataCollection.Rows[i].Cells[firstColumn].Value
value: findCell(data.Rows[i].Cells, firstColumn).Value
});
}
//if (columns.indexOf({field: secondColumnValue}) == -1) {
if (i < 12) {
columns.push({
field: secondColumnValue,
editableCellTemplate: "<input ng-class=\"'colt' + col.index\" ng-input=\"COL_FIELD\" ng-blur=\"lostFocus()\" ng-model=\"COL_FIELD\" ng-change=\"dataChanged(col,row,row.entity)\"/>",
enableCellEdit: true
});
}
rowItems.push({
name: secondColumnValue,
value: findCell(data.Rows[i].Cells, secondColumn).Value
});
previusFirstColumnValue = firstColumnValue;
}
for (var k = 0; k < rowItems.length; k = k + 1) {
rowArray[rowItems[k].name] = rowItems[k].value;
}
// $scope.columns = columns;
pivotedArray.PivotedRows.push( rowArray);
return {data: pivotedArray, cols: columns};
};
plnkr: http://plnkr.co/edit/ZqC7696xGbUtuWGIvnYs?p=preview
EDIT: The data correlation rows<-> columns is correct, I suspect there is something wrong with data in the pivotedArray.PivotedRows array.
It turned out that moving the code to a new plnkr made the difference. Now, thats a few hours of my life that I want back :)