Update $scope with $resource - angularjs

Why is only the one that don't use $resource.get() work? I am using kendo-angular to update. Has this something to do with async? The main variable looks exactly the same so this has to have something to do with $resourse. What am I missing`
This works:
app.controller('SubjectCntrl', ['$scope', 'categoryService', function($scope, categoryService) {
var main = categoryService.getCategories();
var subjects = {
data : [main]
};
$scope.subjects = {
dataSource: subjects
};
}]);
This does not:
app.controller('SubjectCntrl', ['$scope', 'categoryService', 'ApiFactory', function($scope, categoryService, ApiFactory) {
ApiFactory.get(function(categoriesData) {
var main = categoryService.getCategories();
var subjects = {
data : [main]
};
$scope.subjects = {
dataSource: subjects
};
});
}]);
The factory:
app.factory('ApiFactory', ['$resource', function($resource) {
return $resource('http://localhost:8080/rest/forum/categories/1');
}]);
Service:
app.service('categoryService', ['$resource', function($resource){
this.getCategories = function(){
var farmingSubjects = [ {text: "Poteter", spriteCssClass: "subject"}, {text: "Agurk", spriteCssClass: "subject"} ];
var forestSubjects = [ {text: "Tall", spriteCssClass: "subject"}, {text: "Gran", spriteCssClass: "subject"} ];
var animalSubjects = [ {text: "Hundar", spriteCssClass: "subject"}, {text: "Katter", spriteCssClass: "subject"} ];
var farming = { text: "Jordbruk", items: farmingSubjects };
var forest = { text: "Skogshold", items: forestSubjects };
var animals = { text: "Dyrebruk", items: animalSubjects };
var subjects = [farming, forest, animals ];
var main = { text: "Huvudemner", expanded: true, items: subjects};
return main;
};
}]);
Edit: The success function is called without doubt.
ApiFactory.get(function(data){
console.log('success, got data: ', data);
}, function(err){
alert('request failed');
});

I think the second case is not working because you ApiFactory call is failing. The callback you have declared is for success.

Related

angularJS service object property undefined

I have a controller using a service chartFactory.chartData property to give some data to view. The problem is that the factory is returning the object before the chartFactory.chartData function has time to return the data from the back end, so the property is undefined.
I understand this is an async issue, but I'm not sure how to handle it between a factory and a controller.
chartFactory.js
app.factory('chartFactory', ['$http', '$interval', function($http, $interval) {
var service = {
get chartData() {
$http.get('/portfolio/get-chart-data')
.then(function(response) {
console.log(response.data, 'response data') //logging after undefined message
return response.data
})
}
}
return service
}])
chartController.js
app.controller('chartCtrl', function($scope, $timeout, $http, chartFactory) {
$scope.chartData = chartFactory
$scope.height_chart = window.innerHeight * 0.4
$scope.labels = chartFactory.chartData[0]; //undefined
$scope.series = chartFactory.chartData['GDAX Value']; //undefined
$scope.data = [
chartFactory.chartData[1] //undefined
];
$scope.onClick = function(points, evt) {
console.log(points, evt);
};
$scope.datasetOverride = [{
yAxisID: 'y-axis-1'
}];
$scope.options = {
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
id: 'y-axis-1',
// type: 'linear',
display: true,
position: 'left',
ticks: {
beginAtZero: false,
callback: function(value, index, values) {
if (parseInt(value) >= 1000) {
return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return '$' + value;
}
}
}
}],
xAxes: [{
display: false
}]
}
}
})
Change your controller as,
chartFactory.chartData().then(function(response) {
$scope.labels = getchartData .response.data[0];
$scope.series = chartFactory.response.data['GDAX Value'];
});

Capturing checkbox values to table

I'm trying to create a form that will capture input, select and checkbox values and post them to a table. Everything seems to be working fine, with the exception of the checkboxes. What am I doing wrong?
https://jsfiddle.net/mujaji/uvkzmyox/8/
var app = angular.module("myapp", []);
app.controller("ListController", ['$scope', function($scope) {
$scope.jobtypes = ['accountant', 'janitor', 'ceo', 'receptionist'];
$scope.hobbies = [{name: "long walks on the beach", id: "1", isChecked: false},{name: "eating cheese", id: "2", isChecked: false},{name: "writing haikus", id: "3", isChecked: false},{name: "looking for bigfoot", id: "4", isChecked: false},{name: "watching police academy", id: "5", isChecked: false}];
$scope.personalDetails = [
{
'fname':'Muhammed',
'lname':'Shanid',
'jobtype': 'ceo',
'email':'shanid#shanid.com',
'active': true,
'hobbies': [{name: "long walks on the beach", id: "1"},{name: "watching police academy", id: "5"}]
},
{
'fname':'John',
'lname':'Abraham',
'jobtype': 'accountant',
'email':'john#john.com',
'active': true,
'hobbies': [{name: "writing haikus", id: "3"},{name: "looking for bigfoot", id: "4"}]
},
{
'fname':'Roy',
'lname':'Mathew',
'jobtype': 'janitor',
'email':'roy#roy.com',
'active': false,
'hobbies': [{name: "eating cheese", id: "2"}]
}];
$scope.addNew = function(personalDetails){
$scope.personalDetails.push({
'fname': personalDetails.fname,
'lname': personalDetails.lname,
'email': personalDetails.email,
'jobtype': personalDetails.jobtype,
});
$scope.PD = {};
};
$scope.remove = function(){
var newDataList=[];
$scope.selectedAll = false;
angular.forEach($scope.personalDetails, function(selected){
if(!selected.selected){
newDataList.push(selected);
}
});
$scope.personalDetails = newDataList;
};
$scope.checkAll = function () {
if (!$scope.selectedAll) {
$scope.selectedAll = true;
} else {
$scope.selectedAll = false;
}
angular.forEach($scope.personalDetails, function (personalDetails) {
personalDetails.selected = $scope.selectedAll;
});
};
}]);
The problem your facing is caused by the fact that hobbies and their checked state is outside the scope of your addNew(personalDetails) function.
Although not ideal for angular, something like this would work:
$scope.addNew = function(personalDetails) {
//get all checked hobbies
let selectedHobbies = [];
$scope.hobbies.forEach(function(hobby) {
if (hobby.isChecked) selectedHobbies.push(hobby);
});
$scope.personalDetails.push({
'fname': personalDetails.fname,
'lname': personalDetails.lname,
'email': personalDetails.email,
'jobtype': personalDetails.jobtype,
'hobbies': selectedHobbies
});
$scope.PD = {};
};
EDIT
The answer above is really a pure javascript approach to filtering by selected hobbies. A more 'angular' approach would be to break your filter logic out into its own function so that you're not mixing concerns. For example:
Add the 'filterFilter' dependency to your controller:
app.controller("ListController", ['$scope','filterFilter',
function($scope, filterFilter) { ... }
then in your controller, define an array to hold your selected hobbies and add a filter helper to filter by isChecked:
$scope.hobbiesSelection = [];
$scope.selectedHobbies = function selectedHobbies() {
return filterFilter($scope.hobbies, { selected: true });
};
place a watch on the hobbies object to watch for changes to selected hobbies:
$scope.$watch('hobbies|filter:{isChecked: true}', function (hobbies) {
$scope.hobbiesSelection = hobbies;
}, true);
and finally, you can update your addNew() method to simply be:
$scope.addNew = function(personalDetails){
$scope.personalDetails.push({
'fname': personalDetails.fname,
'lname': personalDetails.lname,
'email': personalDetails.email,
'jobtype': personalDetails.jobtype,
'hobbies': $scope.selectedHobbies
});
$scope.PD = {};
};
So while there is a bit more code (and complexity) there for this example, you are separating the logic from the data a bit better. There is working example here: https://jsfiddle.net/mt0tvkwm/

injecting a list into a json format

I'm new with angularJs and i want to inject a list of string that i get it using a restful web service into a jSON list.
And how can the connections list could proceed object returned by getAllConnectedApp.
angular
.module('theme.core.navigation_controller', ['theme.core.services'])
.controller('NavigationController', ['$scope', '$location', '$timeout', '$filter', '$http', '$cookieStore', '$interval',
function($scope, $location, $timeout, filter, $http, $cookieStore, $interval) {
'use strict';
$scope.filterOptions = {
filterText: '',
useExternalFilter: true
};
$scope.connections = [];
$scope.menu = [{
label: 'HOME',
iconClasses: 'glyphicon glyphicon-home',
url: '#/'
}, {
label: 'ORACLE MONITORING',
iconClasses: 'glyphicon glyphicon-unchecked',
children: [{
label: 'SESSIONS',
url: '#/general'
}, {
label: 'ADVANCED MONITORING',
url: '#/advanced-monitoring'
}, {
label: 'CONFIGURATION',
url: '#/configuration'
}]
}, {
label: 'CODE TRACER',
iconClasses: 'glyphicon glyphicon-check',
children: [{
label: 'ADD CONNECTION',
url: '#/addConnectionApp'
},
for (var i = 0; i < $scope.connections.length; i++) {
{
label: $scope.connections[i],
url: '#/codetracer',
}
}
]
//url: '#/codetracer'
}];
$scope.getAllConnectedApp = function() {
console.log("GET ALL CONNECTED APPLICATIONS...");
$http.get("http://localhost:8090/api/personne/allConnection")
.success(function(connections) {
console.log(connections);
$scope.connections = connections;
});
};
}
]);
you have got syntax error over there, you can't have a loop inside object literal definition.
also, you portably want to update the menu only after getting back the response from the sever.
because your code was illogical as by the time you execute the loop, scope.connections is still an empty array.
something like this:
angular
.module('theme.core.navigation_controller', ['theme.core.services'])
.controller('NavigationController', ['$scope', '$location', '$timeout', '$filter', '$http', '$cookieStore', '$interval',
function ($scope, $location, $timeout, filter, $http, $cookieStore, $interval) {
'use strict';
$scope.filterOptions = {
filterText: '',
useExternalFilter: true
};
$scope.connections = [];
var connectionsMenu = [{
label: 'ADD CONNECTION',
url: '#/addConnectionApp'
}];
$scope.menu = [{
label: 'HOME',
iconClasses: 'glyphicon glyphicon-home',
url: '#/'
}, {
label: 'ORACLE MONITORING',
iconClasses: 'glyphicon glyphicon-unchecked',
children: [{
label: 'SESSIONS',
url: '#/general'
}, {
label: 'ADVANCED MONITORING',
url: '#/advanced-monitoring'
}, {
label: 'CONFIGURATION',
url: '#/configuration'
}]
}, {
label: 'CODE TRACER',
iconClasses: 'glyphicon glyphicon-check',
children: [connectionsMenu]
//url: '#/codetracer'
}];
$scope.getAllConnectedApp = function () {
console.log("GET ALL CONNECTED APPLICATIONS...");
$http.get("http://localhost:8090/api/personne/allConnection")
.success(function (connections) {
console.log(connections);
$scope.connections = connections;
for (var i = 0; i < connections.length; i++) {
connectionsMenu.push({
label: connections[i],
url: '#/codetracer',
});
}
});
};
}
]);

Angular ui-grid Set Filter at Runtime

I'm having trouble setting a column filter at runtime via user interaction. Here's my attempt:
http://plnkr.co/edit/Ynesaq5o3HNsF5r8rXQf?p=preview
$scope.setFilter = function() {
$scope.gridApi.grid.columns[1].filters[0] = {
condition: uiGridConstants.filter.EXACT,
placeholder: '',
term: 'female'
};
$scope.gridApi.core.notifyDataChange(uiGridConstants.dataChange.ALL);
$scope.gridApi.grid.refresh();
}
The field is set and the term is added to the field but the data is not refreshed.
Any ideas?
In the original plunker I had a useExternalFiltering set to true. Removing that fixed the issue I was having.
var app = angular.module('app', ['ngTouch', 'ui.grid']);
app.controller('MainCtrl', ['$scope', '$http', '$interval', 'uiGridConstants', function ($scope, $http, $interval, uiGridConstants) {
$scope.filterText = 'female';
$scope.gridOptions = {
enableFiltering: false,
columnDefs: [
{ name: 'name', enableFiltering: false },
{ name: 'gender' },
{ name: 'company', enableFiltering: false}
],
onRegisterApi: function( gridApi ) {
$scope.gridApi = gridApi;
}
};
$http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/100.json')
.success(function(data) {
$scope.gridOptions.data = data;
});
$scope.setFilter = function() {
console.log($scope.gridApi.grid.columns[1]);
$scope.gridApi.grid.columns[1].filters[0] = {
condition: uiGridConstants.filter.STARTS_WITH,
term: $scope.filterText
};
$scope.gridOptions.enableFiltering = true
$scope.gridApi.grid.refresh();
}
}]);

how to get a particular location on google maps with markers from a angular dropdown list

I am trying to do some location search on google maps,its like i am having a angular multi-select drop-down where i am having several locations, if i select a single location or more ,i have to show them on maps using markers,and how to get our current location any suggestions on how to do it please.
Dropdown code
<div class="m-r"
ng-dropdown-multiselect=""
options="locations"
selected-model="search.locations"
extra-settings="multiSelectSettingsFunction"
translation-texts ="locationsTexts"
settings="selectSettings">
</div>
Google maps code
<ui-gmap-google-map center="map.center" refresh="true" zoom="map.zoom" draggable="true" data-tap-disabled="true">
<ui-gmap-window show="map.window.show" coords="map.window.model" options="map.window.options" closeClick="map.window.closeClick()">
<div style="color: black" background-color="#337ab7">
{{map.window.title}}
{{map.window.venue}}
</div>
</ui-gmap-window>
<ui-gmap-markers idkey="marker.id" models="map.markers" coords="'self'" doCluster="false" fit="'true'" icon="'icon'" events="map.markersEvents " options="'options'"></ui-gmap-markers>
</ui-gmap-google-map>
controller.js
app.controller("MainController", [ '$anchorScroll', '$scope', '$http', '$modal', '$log', '$timeout', '$location', '$rootScope', '$window','$mdSidenav' , function ($anchorScroll, $scope, $http, $modal, $log, $timeout, $location, $rootScope, $window,$mdSidenav) {
$scope.searchBack = window.sessionStorage.searchBack;
$scope.search = {
pax: '',
data: '',
locations : [],
distance : []
}
$scope.$watch('search.locations', function(newVal, oldVal){
//console.log(newVal);
//$scope.setSearch();
}, true);
$scope.locationsTexts = {
buttonDefaultText: 'Locations',
dynamicButtonTextSuffix: 'Locations',
}
$scope.multiSelectSettings = {
displayProp: 'locations',
idProp: 'locations',
scrollableHeight: '256px',
scrollable: true,
enableSearch: true,
buttonDefaultText: 'asd',
dynamicButtonTextSuffix: 'Locations',
//showCheckAll: false,
};
$scope.locations = [
{id: 1, label: "kothapet"},
{id: 2, label: "Dsnr"},
{id: 3, label: "Malakpet"},
{id: 4, label: "Chadarghat"},
{id: 5, label: "Koti"},
{id: 6, label: "abids"}
];
Maps Controller
app.controller('MapController2', function($scope, $rootScope, $http) {
var data = {};
data.map = {
zoom: 16,
center: {
latitude: 17.399,
longitude: 78.52
},
markers: [
{
id: 1,
latitude: 17.3762,
longitude: 78.5461,
title: 'Location:Nagole',
venue:'Venue: Ng builders'
},
{
id: 2,
latitude: 17.3710,
longitude: 78.5410,
title: 'Location:Kothapet',
venue:'Venue: A Builders'
},
{
id: 3,
latitude: 17.3688,
longitude: 78.5247,
title: 'Location:Dilsukhnagar',
venue:'Venue: B Builders'
},
{
id: 4,
latitude: 17.3667,
longitude: 78.500,
title: 'Location:Malakpet',
venue:'Venue: C Builders'
}],
markersEvents: {
click: function(marker, eventName, model, arguments) {
console.log('Marker was clicked (' + marker + ', ' + eventName);//+', '+mydump(model, 0)+', '+mydump(arguments)+')');
$scope.map.window.model = model;
$scope.map.window.model = model;
$scope.map.window.title = model.title;
$scope.map.window.venue = model.venue;
$scope.map.window.show = true;
}
},
window: {
marker: {},
show: false,
closeClick: function() {
this.show = false;
},
options: {}, // define when map is ready
title: ''
}
};
//$scope.window = false;
$scope.onMarkerClicked = function (m) {
//this.windowOptions = !this.windowOptions;
console.log('Marker was clicked');
console.log(m);
};
$scope.closeClick = function () {
this.window = false;
};
$scope.map = data.map;
});
1) To resolve location by address name utilize Google Maps Geocoding API, for example:
var resolveAddress = function(address) {
var deffered = $q.defer();
$http({
url: 'http://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&sensor=false',
method: 'GET'
}).
success(function(data) {
deffered.resolve(data);
}).
error(function(error) {
deffered.reject();
});
return deffered.promise;
};
2) For angularjs-dropdown-multiselect component you could utilize events to add events what the directive fires, for example onItemSelect which triggers once the item is selected:
<div class="m-r"
ng-dropdown-multiselect=""
options="locations"
selected-model="search.locations"
translation-texts="locationsTexts"
settings="selectSettings"
events="{ onItemSelect: showItemOnMap }">
</div>
$scope.showItemOnMap = function(item) {
//...
};
The following demo demonstrates how to display markers on map from items selected in angularjs-dropdown-multiselect control
Demo

Resources