I am trying to use angular-resource.js file in my demo .I am retrieving
data from json file using $resource and display my data using ng-repeat .But Each item I added one button (info text button).I need to get it infomation using $resource property.I am sending ID on click function .but when I am using $resource property it gives error to me
$scope.getIn=function(id){
// alert(id)
$scope.oneUser = Entry.get({user: id});
console.log($scope.oneUser)
}
here is my code
http://plnkr.co/edit/lB11oQkQjbILK36u8V25?p=preview
If i understand correctly what you are trying to achieve this should solve it:
angular.module('app',['ngResource']).controller('a',function($scope, GetData){
// read data from factory and store it in $scope.posts
GetData.then(
function successCallback(data) {
$scope.posts = data.data;
},
function errorCallback(response) {
console.log(response); // handle any errors
});
// buttonclick to return the values from the selected id
$scope.getIn = function(id){
angular.forEach($scope.posts, function(value) {
if(value.id === id)
{
$scope.selectedValue = value;
}
})
};
console.log($scope.posts)
})
.factory('GetData', function($http){ // use http to read the json
return $http.get('data.json');
});
And the html:
<body ng-app='app' ng-controller='a'>
<div ng-repeat='p in posts'>
<span>{{p.name}}</span>
<button ng-click=getIn(p.id)>info</button>
</div>
{{selectedValue}}
</body>
Related
I want to show the following JSON in an Angular page :
{"_id":"58b11","name":"Somename","city":"Paris","number":456789123,"__v":0}
I get this data by clicking on a link in an Angular page:
<td ng-click="getData(user._id)">
{{user.name}}
</td>
I am able to get the data from the db and show in the angular page in proper HTML. Now when I click on the link, i get the desired data in JSON on the page http://localhost:8080/api/students/58b11. I want to be able to use Angular {{}} to show the data in proper HTML format.
Angular :
//Created Student factory like this:
app.factory('Student', function($resource) {
var data = $resource('/api/students/:id', { id: '#_id' }, {
update: {
method: 'PUT'
}
});
return data;
});
//controller:
app.controller("dummy2", function($scope, $http, Student, $window){
$scope.getData = function(userID){
$window.location.assign("/api/students/"+userID);
}
)};
NodeJs:
app.use('/api', require('./routes/api'));
Thanks.
I am trying to display the items using ng-repeat and when the list is initailly loading , trying to call another service to get the details about the first item.
Here is my code:
<div ng-repeat="item in itemList">
<div ng-click="setCurrentItem(item,$index)" ng-init="initCurrentItem(item,$index)">
item.id
</div>
</div>
In controller:
function init(){
itemService.loadItem();
}
$scope.itemList = function(){
return itemService.getItemsList();
}
from this service I am getting the following data :
itemName:x001,
item.id:10
itemName:x002,
item.id:20,
itemName:x003,
item.id:30.
I am calling another service to get itemDetails.
$scope.currentItemDetails ={};
$scope.currentItemDetails.id ='';
$scope.initCurrentItem(item.index){
if(scope.currentItemDetails.id === ''){
$scope.setCurrentItem(item.index);
}
}
$scope.setCurrentItem = function(item,index){
item.index = index;
itemService.loadItemDetails(item.id).then(function(response){
if(angular.isDefined(response)){
$scope.currentItemDetails = response.data;
}
});
when the list loading initailly and calling initCurrentItem, the currentItemDetails holding last item (itemName:x003,id:30). ng-repeat is repeat the values without waiting response from the service. How do I wait in the loop until I get response from first item?
Just use the same logic in init method as you have in the other example - with .then( etc. And assign value to the repeating variable itemList. Then table HTML will be refreshed automagically when the data arrives and Promise will be resolved:
<div ng-repeat="item in itemList">
function init(){
itemService.loadItem().then(function(response){
if(angular.isDefined(response)){
$scope.itemList = response.data;
}
});
}
UPD
try calling initCurrentItem after the data is loaded
function init(){
itemService.loadItem().then(function(response){
if(angular.isDefined(response)){
$scope.itemList = response.data;
//here we iterate received array $scope.itemList and call initCurrentItem on each of them
$scope.itemList.forEach(function(item, i){
$scope.initCurrentItem(item, i);
});
}
});
}
I'm trying to submit a form from a HTML page using angular.
My HTML code is:
<form role="search">
<input type="text" ng-model="searchSring">
<button type="submit" ng-click="searchPerson(searchString);">Get it!
</button>
</form>
The searchPerson function is calling some PHP page using Ajax and data is successfully retrieved from it.
What I want is when the user has clicked the Get it! button, he should be routed to another HTML page where I would like to display the results. I've tried using "action=" in the form and even calling window.location once Ajax completed to route to the next page. Every time the result is cleared. I've tried using factory with get/set, but this too clears the data on the second page after the window.location call.
Here's the factory code:
myApp.factory('searchService', function(){
var searchService = {};
var mySearchResult = {};
searchService.set = function(searchResult){
mySearchResult = searchResult;
}
searchService.get = function(text){
return mySearchResult;
}
return searchService;
});
CONTROLLER
myApp.controller('OnlineCVController', function($scope, searchService) {
$scope.searchPerson = function(personString) {
$.ajax({
url: "mySearch.php",
type: 'POST',
data: { Person: personString },
async: false, success: function (result) { searchService.set(result);
console.log(result);
window.location = "search.html";
}, error: function (result) { } });
}
Can anyone guide me further?
I want $http.get method to work when a form is submitted.
Here is my code. The object $scope.questions is being set when the method is called but the data doesn't show up in the div. Moreover, when the $http.get method is outside the signIn() function it works just fine.
$scope.signIn = function(data) {
$location.path('/profile');
var url = "database/fetch_data.php?query=";
var query = "Select * from question where userId=2";
url += query;
$http.get(url).success(function(questionData) {
$scope.questions = questionData;
console.log($scope.questions);
});
};
<div>
User Profile
<br/>Question Posted
<br/>
<input ng-model="query.title" id="value" type="text" placeholder="Search by Title..." ">
<div>
<ul>
<li ng-repeat="question in questions | filter: query ">
{{question.title}}
</li>
</ul>
</div>
<br/>
</div>
You need to move your $location.path('/profile') inside your http request. Remember that a http request is async call. You should redirect after getting the data not before.
$scope.signIn = function(data) {
var url = "database/fetch_data.php?query=";
var query = "Select * from question where userId=2";
url += query;
$http.get(url).success(function(questionData) {
$scope.questions = questionData;
console.log($scope.questions);
$location.path('/profile');
});
};
If you're redirecting to another route with a completely separate scope you will lose any scope you're setting in the success handling.
From what I'm reading you're clicking a button to do an action. After that action you're redirecting to another page with a separate controller and trying to persist the data.
Unfortunately, Angular hasn't figured out a great way to do this. The easiest way to persist data through controllers and scope is to create a service that will store it in one controller and grab it in another controller.
For instance:
$scope.signIn = function(data) {
var url = "database/fetch_data.php?query=";
var query = "Select * from question where userId=2";
url += query;
$http.get(url).success(function(questionData) {
$location.path('/profile');
storageService.store("question", questiondata)
});
};
Your new factory to persist data through:
angular.module('moduleName').factory('storageService', [
function () {
return {
store: function (key, value) {
localStorage.setItem(key, JSON.stringify(value));
},
get: function(key) {
return JSON.parse(localStorage.getItem(key));
},
remove: function(key) {
localStorage.removeItem(key);
}
}
}
]);
Other controller to access data:
$scope.question = storageService.get("question");
// remove localstorage after you've grabbed it in the new controller
storageService.remove("question");
An alternative to doing the somewhat 'hacky' way of using localStorage to persist data through controllers is to use ui-router and have a resolve on the route you're redirecting to.
For instance:
$scope.signIn = function(data) {
$state.go('profile');
};
In your route file:
.state('profile', {
url: '/profile'
controller: profileControllerName,
templateUrl: 'profileHtmlTemplate.html',
resolve: {
'questions': [function() {
var url = "database/fetch_data.php?query=";
var query = "Select * from question where userId=2";
url += query;
$http.get(url).success(function(res) {
return res.data;
});
}]
}
}
In your profile controller:
Inject your 'questions' resolve into your controller and assign `$scope.question = questions;
This will make the HTTP call as soon as you click the route, return the data if successful, then render the page. It will NOT render the page if the resolve does not return success. This will ensure your data will be loaded before you load the page that depends on that data.
I would highly recommend using services to hold your HTTP calls for specific parts of your application. If you have a GET questions, POST question, PUT question. I would create a questionService and make all my HTTP methods there so you don't have to clutter your routes. You would only have to call:
.state('profile', {
url: '/profile'
controller: profileControllerName,
templateUrl: 'profileHtmlTemplate.html',
resolve: {
'questions': [function() {
return questionService.getQuestions(id).then(function(res) {
return res.data;
})
}]
}
}
Folks,
I have following Button Click which calls AngularJS $scope.getCustomerById method
<div><button type="button" ng-click="getCustomerById(cust.CustomerNumber);">detail of
{{cust.CustomerNumber}} customer</button>
</div>
Now my Controller JS code for getCustomerById is as below
$scope.getCustomerById = function (id) {
CustomerService.getCustomer(id)
.then(function (data) {
$scope.customer = data.data; //which returns data correctly
$location.path('Customer/' + $scope.customer.CustomerNumber.trim());
}, function (error) {
alert(error);
});
};
and it goes to Designated View as well, but this View Does not render customer data. My CustomerView is very simple,
<div data-ng-controller="CustomerController">
{{ customer.CustomerNumber }}//this doesn't show anything, eventhough $scope.customer
//is set in controller as above
</div>
Any help will be really appreciated.