Angular Js call multiple times controller method and display output in view - angularjs

I am very new to angular js and trying to fetch results from a service in loop and want to show in View.
I believe the flow will be:
View calls controller with last got entry (controller shouldn't know user want to view more data or not so view will control when to stop.). Controller will be calling a service/factory to retrieve the results.
Please suggest if the workflow is correct or I'm mixing view with controller work. Or somehow I believe controller should control logic for how much data has to be collected and just update some local variable with it. View should use that variable to reflect it on view side.
Second thing: How I can retrieve results from Controller in loop from View.
Edit:
How I can get persons values from controller:
If i want to get persons from this controller. How should i ? I'm doing something wrong here. I am not sure if I should call methods from view?
angular.module('app.dashboard.dashboardControllers', []).
controller('dashboardController', ['$scope',
function ($scope) {
$scope.persons = $scope.showAssets(null);
$scope.showAssets = function (lastExecutedId) {
var persons_1 = [{
"id": 860,
"firstName": "Superman",
"lastName": "Yoda"
}, {
"id": 870,
"firstName": "Foo",
"lastName": "Whateveryournameis"
}, {
"id": 590,
"firstName": "Toto",
"lastName": "Titi"
}, {
"id": 803,
"firstName": "Luke",
"lastName": "Kyle"
}];
return persons_1;
};
}
]);

Your flow is correct: View -> Controller -> Service = Results last stored in Service
Second Thing: To get results from the view, such as user input elements, those elements need to be bound to some $scope inside the controller.
The power of Angular is you will never need to call for these values once you bind them correctly. Your view will always reflect the current values of $scope objects or whatever else has a bind on it.
Look this page for descriptions on the popular ways to bind elements:
http://www.javabeat.net/angularjs-ng-model-ng-bind/

Related

How to convert string into JSON data in view part of angularjs

Hi I have this data in JSON form, and I want to convert this data of option into json so that i can call optionName, optionSubName in a view part of angularjs
[
{
"heading": "MakeUp Type / Selection",
"option": "{"optionName":"Bridal Makeup","optionSubName":"Engagement,Tika / Godh Bharai,Ring Ceremony","optionDesc":""}",
"values": null
},
{
"heading": "Makeup Type",
"option": "{"optionName":"Experienced","optionSubName":"","optionDesc":{"products":"Bobbie Brown,Makeup Forever and Premium Makeup Products","Makeup_Include":"Straightening,Blow Drys,Tong Curls,Updo's","Drapping":"Yes","Lashes":"Yes","Nail_Polish_Change":"Yes","Extension_Available":"Yes","Airbrush_Available":"Yes"}}",
"values": null
}
]
I have already tried this but this is not working by using ng-repeat i have using this {{data.option.optionName | JSON}} but this is not working in my view part of angularjs, Please help me out how to reach at my goal ?
Use AngularJS forEach:
angular.forEach(object, iterator, [context])
object: The object interate over.
iterator: The iterator function or the code.
context: Object to become context (using this) for the iterator function.
var app = angular.module('app', []);
app.controller('AppController', ['$scope', '$http',
function($scope, $http) {
$http.get('json/array.json').success(function(data) {
$scope.array = data;
angular.forEach($scope.array, function(x){
console.log(x.optionName);
})
});
});
}
]);

How can i use JSON stringify in Angular?

i'm newbie to Angular. I'm trying to get Json data which written like that :
id:1,
name: "Friends",
type: "Group",
Now, i know i can't use this kind of data unless i add double quotes - like that (it's the only way it is working):
"id":1,
"name": "Friends",
"type": "Group",
What is the best way to parse JSON in Angular?
I've tried to combine JS , but it didn't work :
app.controller('contacts', function ($scope,$http,$log) {
$http.get('http://localhost/Angular-Http-exercise/db.json')
.then(function(response) {
$scope.myData = function() {
return JSON.stringify(response.data)
};
$log.info(response.data.name);
});
});
You can use angular.fromJson and angular.toJson for that purpose:
scope.myData = function(){
return angular.fromJson(response.data);
}
However JSON is a global variable and you should have access to it, since angular uses the same.
https://docs.angularjs.org/api/ng/function/angular.fromJson
https://docs.angularjs.org/api/ng/function/angular.toJson
Roy, your question is What is the best way to parse JSON in Angular? JSON will not differ from one framework/language to another and there's no best way to write JSON.
If you want to see if your JSON is formatted correctly check out tools like: https://jsonformatter.curiousconcept.com/

Access to nested object in JSON ,select the right value in a dropdownlist (Angularjs)

I am a beginner in AngularJS. I used the $resource service to get a specific object of type person based on its id from the server in order to update this object.
Resource service:
moduleName.factory('Person', function ($resource) {
return $resource('/application/person/:id', {}, {
show: { method: 'GET' , params: {id: '#id'}},
});
});
The object that I received and it displayed in my browser using the {{}} is:
{
"id": "560cf96ee85532035928889e",
"firstName": "Christiane",
"gender": "Male",
"flight": {
"id": null,
"arrivalDate": "2015-01-05 11:30",
"arrivalAirport": {
"name": "Frankfurt"
},
"stopovers": []
}
}
In this form I have a dropdownlist that contains the Airport list, I expect that the value of the arrivalAirport will be selected in this dropdown list, but no value was selected, I try to set the selected value of this dropdown list in the AngularJs controller of this view.Before setting the value of this object I try to access to their value by this code inside the controller.
moduleName.controller('PersonDetailController',function ($scope, $routeParams, Person,$location) {
$scope.person = Person.show({id: $routeParams.id});
console.log($scope.person.flight.arrivalAirport);
});
when I want to get the value of the object flight.arrivalAirport nested in person object I got this error.
TypeError: Cannot read property 'arrivalAirport' of undefined
How can I display the right value selected in the dropdown list and how can I access to the other object like stopovers array in order to update their values?
Thank you.
When you call console.log Person's data hasn't been retrieved yet. You should do something like this:
$scope.person = Person.show({id: $routeParams.id}, function(person) {
console.log(person.flight.arrivalAirport);
});
In general, any code working on data received asynchronously can't be put right after the call because it's very unlikely that data has been retrieved at that point, you should use callbacks and promises.
Your view should update automatically, and you said it does, at least for the part showing the json. In order to make the dropdown update you should bind its values to a property inside $scope.person
If the dropdown doesn't update then there must be some other error and you might need to post the dropdown's code too.
If you want to manually update the dropdown's list instead then you need to put the relevant code inside the callback (the function i added to "person.show" in the code above) in order to make it work

AngularJS binding not occurring on page until a user action

I've got my first angular app which displays some data from a list via ng-repeat.
The controller for the view sets a few variables to scope - some directly in the function and another from an API call.
The data from the in function load is showing up in that ng-repeat. The data from the service call doesn't show up (debugging shows the function is being called and data returned and set in scope).
I've got a filter on and if I type anything in it then the data shows up. Or when I click to another view the data flashes onto the page briefly before it loads the new view.
Here is some view code (the items works, venues does not):
<div ng-repeat="item in items">
{{ item.firstName }}
</div>
<div ng-repeat="venue in venues">
{{ venue.details }}
</div>
And here is the controller (data is coming back from the call):
$scope.items = [
{ "firstName": "John", "lastName": "Doe" },
{ "firstName": "Anna", "lastName": "Smith" },
{ "firstName": "Peter", "lastName": "Jones" }
];
var client = new WindowsAzure.MobileServiceClient("url", "key");
var query = client.getTable("venues").read().done(function (results) {
$scope.venues = results;
}, function (err) {
alert("Error: " + err);
});
I'm wondering if maybe the binding is happening before the data is returned from the API?
I added a div and this line into the function and it is printing the results to the page no issues:
document.getElementById("venueslist").innerHTML = JSON.stringify(results);
Thank you for reading.
Looking at your code client.getTable doesn't look like it is using any of angularJs $http or $timeout service. So you will have to wrap the assignment in scope.$apply() so that the $digest cycle is run and the bindings are updated in the view.
var query = client.getTable("venues").read().done(function (results) {
$scope.$apply(function () {
$scope.venues = results;
});
}, function (err) {
alert("Error: " + err);
});
Side note: why are you doing JSON.parse(JSON.stringify(results)), you can directly use results if it is a json object.

Angular Factory Manipulating Data (CRUD) with function in the Factory

I have a simple Angular App that uses a factory to pull a list of items from a "JSON" file. Eventually this will be connected to a database but for now I'm starting with just pulling from a static file. The JSON file contains an array of items. I'm really trying to understand how do I get a reference to my data in the factory after the promise has been returned to the controller.
My Factory is setup as follows:
angular.module("myApp").factory("ServiceTypeFactory", ['$http', function ($http ) {
return {
ServiceTypes: function () {
return $http.get('json/servicetypes.json').success
(
function (data) {
return data;
});
},
find: function (id) {
return _.findWhere(data, {ID:id}); // Not sure how to get access to the data
}
}
}]);
This works great I can share the Factory across multiple controllers. The part I'm missing is how do I reference a specific array item from my json file and update it in my controller. I'm not following how to get a reference to the actual data so when I modify the item in one controller it the change would be reflected in another controller.
In both of my controllers I have the following code to get a reference to the data initially.
var popService = function (data) {
$scope.ServiceTypes = data;
}
// IF at ANY time the Service Types have not been loaded we will populate them.
if (typeof $scope.ServiceTypes === "undefined") {
ServiceTypeFactory.ServiceTypes().success(popService);
}
My understanding is my $scope.ServiceTypes has really a reference to the data. How do I back in my factory in a function get access to the actual single source of my data. I get that the factory returns the data with functions an object but I'm missing how to reference this data back in my factory to manipulate it. In the future I want to perform CRUD operations on it for the time being I'm just trying to work out the mechanics.
What my JSON file looks like:
{
"serviceTypes": [
{
"ID": "1001",
"ServiceTypeName": "111111",
"Description": "aaaaaaa"
},
{
"ID": "1002",
"ServiceTypeName": "222222",
"Description": "bbbbbbb"
},
{
"ID": "1003",
"ServiceTypeName": "3333333",
"Description": "ccccccc"
},
{
"ID": "1004",
"ServiceTypeName": "444444",
"Description": "dddddddd"
},
{
"ID": "1005",
"ServiceTypeName": "5555555",
"Description": "eeeeeee"
}
]
}
Just needed to clean the code up a little. Watching a couple of quick example on egghead.io made it clear.

Resources