Angularjs using service to pass a parameter to a function - angularjs

I'm fetching a Json with a factory "chapters", so I get the value of the property "json_file" which is another json file that I need to fetch dynamically with the factory "contents". I just need to pass the parameter "json_file" to the second factory, but I get an undefined value.
Maybe I need a service?
This is the first json file:
structure.js
[
{
"title": "Introduction",
"pages": [
{
"title": "Buongiorno",
"type" : "standard",
"json_file" : "cover_1"
},
{
"title": "Introduction",
"type" : "standard",
"json_file" : "cover_1"
}
]
},
{
"title": "Storytelling",
"pages": [
{
"title": "Italian Design & Swiss Watchmaking Expertise",
"type" : "standard",
"json_file" : "cover_1"
},
{
"title": "Interaction",
"type" : "standard",
"json_file" : "cover_1"
}
]
}
]
This is the controller.js
var bControllers = angular.module('bControllers',[]);
bControllers.controller('structureCtrl', function ($scope, $routeParams,chapters,contents){
$scope.indexChapter = 0;
$scope.indexPage = 0;
chapters.list(function(chapters) {
$scope.chapters = chapters;
$scope.pages = [];
$scope.json_file = [];
angular.forEach($scope.chapters, function(chapters,index){
angular.forEach(chapters.pages, function(page,index2){
$scope.pages.push(page);
$scope.json_file.push(page.json_file);
})
});
$scope.currentJson = $scope.chapters[$scope.indexChapter].pages[$scope.indexPage].json_file;
console.log('json-file:'+$scope.currentJson);
return $scope.currentJson;
});
contents.find($scope.currentJson, function(content) {
$scope.content = content;
});
});
And this is the factory.js
var bFactory = angular.module('bFactory',[]);
bFactory.factory('chapters', function($http){
return {
list: function (callback){
$http({
method: 'GET',
url: 'json/structure.json',
cache: true
}).success(callback);
}
}
});
bFactory.factory('contents', function($http){
return{
find:function(json_file, callback){
$http({
method: 'GET',
url: 'json/'+json_file+'.json',
cache: true
}).success(callback);
}
}
})

Related

How to update local json file in angularjs

How do I update local json file using angularjs. My file name is data.json which is location in project folder.
I tried this below way
var data = [{
"Numbers": {
"Number": {
"_Id": "1",
"__text": "201"
}
}
}];
var jsonFileName = "data.json"
factory.updateJsonDataByFileName = function (jsonFileName, data) {
$http.post(jsonFileName, data).then(function successCallback(response) {
var jsonResult = response.data;
deferred.resolve(jsonResult);
}, function errorCallback(error) {
deferred.reject(error);
});
return deferred.promise;
}
My JSON File looks like this below
{
"Numbers": {
"Number": {
"_Id": "1",
"__text": "200"
}
}
}

AngularJS: mocking the service in a controller using Jasmine

Could you please help me to write down the Jasmine(2.0) test code for mock of the service in a Controller as below.
readJsonFactory.js
angular.module('myAssignmentTaskApp')
.factory('readJsonFactory', function ($http) {
var userExists = false;
var responseData = [];
return $http.get('../json/AutoTestDB1.json').then(function (response) {
for (var i=0; i<response.data.StatusTable.length; i++){
responseData.push(response.data.StatusTable[i].RunId);
}
return response;
}).catch(function (error) {
//
})
});
The Controller file readjson.js is as below.
angular.module('myAssignmentTaskApp')
.controller('ReadjsonctrlCtrl', function ($scope,readJsonFactory,$location) {
var testCaseNameFromReadJsonFactory = [];
readJsonFactory.then(function (response) {
for (`var i=0;i<response.data.StatusTable.length;i++`){
testCaseNameFromReadJsonFactory.push(response.data.StatusTable[i].TestScenario);
}
}
})
AutoTestDB1.json
{
"StatusTable": [
{
"RunId": "bah_regression_alternateFlights",
"TestScenario": "BAH - Change Default Search Options",
"Area": "Yes",
"TestCases": [
{
"TestID": "",
"TestName": "VerifyCarDepotPageIsDisplayed_Test",
"Status": [
{
"Release": " R301",
"Runner": "yes",
"Status": "Passed",
"details": [
{
"ResponseTime": "1m 26s 702ms",
"Status": "Passed",
"RecordData": 1511519114413
}
]
}
]
}
]
}
]
}
Please post an apporopriate spac.js file.
Thanks in advance.
You do use the following to mock your service
beforeEach(function() {
angular.mock.module('myAssignmentTaskApp', ($provide) => {
const mockReadJsonFactory = {
};
$provide.constant('readJsonFactory', mockReadJsonFactory);
});
});

How to Read the value of below json in controller.js. As i have to set the value in controller.js only

Let Me know how to access the value of response by looking to the below json data
Login Controller
app.controller('loginController', function($scope,$http, $location,
$rootScope,$window) {
$scope.submit = function(){
$rootScope.userName=$scope.username;
var username=$scope.username;
var password=$scope.password;
$http({
method: 'POST',
url: 'http://localhost:8082/APIGateway/APILoginService/login',
data: jsonData,
headers : {
'Content-Type': 'application/json',
'Orgkey': 'S2lyYW5fcmFqYWdvcGFs'
}
})
.then(function successCallback(response) {
if(response.data.code=="Invalid loginId or password" || response.data.message=="Invalid loginId or password"){
$scope.errorMessage = 'Invalid LoginId/Password';
} else {
$rootScope.loggedIn=true;
$rootScope.userName = response.data.APIUserData;
$rootScope.roleName=response.data.roleName;
}
},
};
});
This is The json data.
{
"APIUserData": [
{
"userID": "deve",
"firstName": "De",
"lastName": "Singh",
"mobileNumber": "990064533",
"emailID": "xyz#gmail.com",
"roleID": 1,
"Org_Id": 1,
"status": 1
}
]
}
I am facing problem because of APIUserData. If i remove it i can easily access the value. can anybody help me in fixing the issue
APIUserData is an array. You could do something like this:
var myResponse = {
"APIUserData": [
{
"userID": "deve",
"firstName": "De",
"lastName": "Singh",
"mobileNumber": "990064533",
"emailID": "xyz#gmail.com",
"roleID": 1,
"Org_Id": 1,
"status": 1
}
]
};
var roleID = myResponse.APIUserData[0].roleID;

Ionic / Angular JS - Get specific values from Reverse Geolocation

I am building an App using Ionic / Angular JS. In a specific tab, the app has the ability to fill some form fields automatically like Street Name, Street Number, etc. My problem is that, in some situations the Street Number for example is not available and data[0].address_components[0].long_name fills the Street Name instead.
Here is the code that I use:
.controller('PetitionsCtrl', function($scope, $cordovaGeolocation, $cordovaCamera, $log, $ionicLoading, $http, $timeout, $compile, Upload) {
$scope.getLocation = function() {
$ionicLoading.show({
templateUrl: 'loading.html',
hideOnStateChange: true
});
var posOptions = {timeout: 15000, enableHighAccuracy: true};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
$scope.lat = position.coords.latitude;
$scope.lng = position.coords.longitude;
$scope.pLat = {value: $scope.lat};
$scope.pLng = {value: $scope.lng};
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng($scope.lat, $scope.lng);
var request = {
latLng: latlng
};
geocoder.geocode(request, function(data, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (data[0] != null) {
$scope.$apply(function () {
$scope.pStreet = {value: data[0].address_components[1].long_name};
$scope.pNumber = {value: data[0].address_components[0].long_name};
$scope.pCity = {value: data[0].address_components[2].long_name};
$scope.pAddress = {value: data[0].formatted_address};
setTimeout(function () {
$ionicLoading.hide();
}, 500);
});
} else {
$log.log("Adresa indisponibila");
setTimeout(function () {
$ionicLoading.hide();
}, 500);
}
}
})
});
};
})
Here is an example response from Google:
{
"results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
{
"long_name" : "Amphitheatre Pkwy",
"short_name" : "Amphitheatre Pkwy",
"types" : [ "route" ]
},
{
"long_name" : "Mountain View",
"short_name" : "Mountain View",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Santa Clara County",
"short_name" : "Santa Clara County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "California",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "94043",
"short_name" : "94043",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
"geometry" : {
"location" : {
"lat" : 37.4224764,
"lng" : -122.0842499
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 37.4238253802915,
"lng" : -122.0829009197085
},
"southwest" : {
"lat" : 37.4211274197085,
"lng" : -122.0855988802915
}
}
},
"place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
"types" : [ "street_address" ]
}
],
"status" : "OK"
}
How can I alter my code so it checks the "types" value before reading a value and leaves it empty if not available. To be more speicifc, instead of using data[0].address_components[0].long_name to get the street number, I would like to get if "types" vale is "street_number".
What I have understood is that if the types value is equal to street_number you want to get the value otherwise you want to put empty as a value ''
geocoder.geocode(request, function(data, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (data[0] != null) {
$scope.$apply(function () {
$scope.pStreet = {value: data[0].address_components[1].long_name};
$scope.pNumber = {value: data[0].address_components[0].types[0] === 'street_number' ? data[0].address_components[0].long_name : ''};
$scope.pCity = {value: data[0].address_components[2].long_name};
$scope.pAddress = {value: data[0].formatted_address};
setTimeout(function () {
$ionicLoading.hide();
}, 500);
});
} else {
$log.log("Adresa indisponibila");
setTimeout(function () {
$ionicLoading.hide();
}, 500);
}
}
})
You have to loop over result set to find a match like:
Angular.forEach(data[0].address_components, function(val, index){
if (val.type[0]=='street_number') {
$scope.pNumber = {value: val.long_name};
}
});
You can use this code to find any other value like city or country etc.
Ryad.iv answer is just checking the first string in the array. For this to work properly you have to check all the elements of the array.
geocoder.geocode(request, function(data, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (data[0] != null) {
$scope.$apply(function () {
$scope.pStreet = {value: data[0].address_components[1].long_name};
$scope.pNumber = {value: data[0].address_components[0].types.indexOf('street_number') !== -1 ? data[0].address_components[0].long_name : ''};
$scope.pCity = {value: data[0].address_components[2].long_name};
$scope.pAddress = {value: data[0].formatted_address};
setTimeout(function () {
$ionicLoading.hide();
}, 500);
});
} else {
$log.log("Adresa indisponibila");
setTimeout(function () {
$ionicLoading.hide();
}, 500);
}
}
})
That's the good way of checking this. With the other answer, if street_name is the second position of the array you will not be inserting it correctly.
Hope it helps

UI-Grid not displaying JSON data?

I have what I think is the correct accessor syntax for binding my UI-Grid control, I don't get any errors or any data. I just get a warning about Mutating the prototype.
My json data structure is like this:
{
"records": [
{
"acctIdInfo": {
"acctId": "257905480",
"acctCode": "ABC10101102",
"acctName": "BIG CORPORATION",
"acctRole": [
"C"
]
},
"acctNameAddr": {
"addressLine": [
"7280 JAMISON ST"
],
"cityName": "VANCOUVER",
"stateCd": "US-WA",
"countryCd": "US",
"postalCd": "97979"
}
}
]
}
The code in my AngularJS controller to bind is:
var app = angular.module('app', ['ui.grid', 'ngResource'])
.factory('jsonDataFactory', function ($resource) {
return {
custData: $resource('data.json', {}, {
query: {method: 'GET', params: {}, isArray: false}
}),
};
});
app.controller('MainCtrl', ['$scope','$resource','jsonDataFactory', function ($scope,$resource, jsonDataFactory) {
$scope.gridOptions = {
enableRowSelection: true,
enableSelectAll: true,
selectionRowHeaderWidth: 35
};
$scope.gridOptions.columnDefs = [
{ name: 'acctIdInfo.acctId' },
{ name: 'acctIdInfo.acctCode'},
{ name: 'acctIdInfo.acctName'},
{ name: 'acctNameAddr.addressLine' }
];
$scope.gridOptions.data = jsonDataFactory.custData.query().records;
$scope.CustomerData = [];
$scope.CustomerData = jsonDataFactory.custData.query();
console.log($scope.CustomerData);
$scope.gridOptions.data = $scope.CustomerData.records;
}]);
Here is my plnk of what I tried -
I think I'm close...
Do assign a data to ui-grid data source once ajax call response comes back. I assumed that you had used $resource, so you can have promise over it to attach callback function.
jsonDataFactory.custData.query().$promise.then(function(response){
$scope.CustomerData = response;
console.log($scope.CustomerData);
$scope.gridOptions.data = $scope.CustomerData.records;
});

Resources