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.
Related
Im getting data in this format from api, but when i try binding it to table using angularjs it is creating empty space instead of values. Im also getting more then one table from some Api's please explain who to bind different datatables in different tables too. thanks
{"Table":
[{
"SchoolId":1,
"schoolname":"Microsoft",
"SCHOOLCODE":"29911583",
"WEBSITE":"JLR",
"USEREMAIL":"faucibus#aliquamiaculislacus.org",
"PHONE":"841-9331",
"ADDRESS1":"682-5760 Felis Street",
"ISACTIVE":0,
"PLANTYPE":3
}]
}
Angular Controller
SMSApp.factory('GetStudentService', function ($http) {
studobj = {};
studobj.getAll = function () {
var stud=[];
stud = $http({ method: 'Get', url: 'http://localhost:58545/api/Student?Studentid=1' }).
then(function (response) {
return response.data;
});
return stud;
};
return studobj;
});
SMSApp.controller('studentController', function ($scope, GetStudentService) {
$scope.msg = "Welcome from Controller";
GetStudentService.getAll().then(function (result) {
$scope.school = result;
console.log(result);
});
});
HTML Code
<tbody ng-controller="studentController">
<tr ng-repeat="schools in school track by $index">
<td>{{schools.SchoolId}}</td>
<td>{{schools.schoolname}}</td>
<td>{{schools.SCHOOLCODE}}</td>
<td>{{schools.WEBSITE}}</td>
<td>{{schools.USEREMAIL}}</td>
</tr>
</tbody>
WHAT I GET
Change in your Angular Controller :
SMSApp.controller('studentController', function ($scope, GetStudentService) {
$scope.msg = "Welcome from Controller";
GetStudentService.getAll().then(function (result) {
/********************* Changed Here ********************/
$scope.school = JSON.parse(result._body); // Or only JSON.parse(result)
$scope.school = $scope.school.table;
});
});
And your HTML Code :
<tbody ng-controller="studentController">
<tr ng-repeat="schools in school track by $index">
<td>{{schools.SchoolId}}</td>
<td>{{schools.schoolname}}</td>
<td>{{schools.SCHOOLCODE}}</td>
<td>{{schools.WEBSITE}}</td>
<td>{{schools.USEREMAIL}}</td>
</tr>
</tbody>
Naming the data school is confusing. Do instead:
GetStudentService.getAll().then(function (data) {
$scope.tableObj = data;
console.log(data);
});
<tbody ng-controller="studentController">
<tr ng-repeat="school in tableObj.Table track by school.SchoolId">
<td>{{school.SchoolId}}</td>
<td>{{school.schoolname}}</td>
<td>{{school.SCHOOLCODE}}</td>
<td>{{school.WEBSITE}}</td>
<td>{{school.USEREMAIL}}</td>
</tr>
</tbody>
From the Docs:
Best Practice: If you are working with objects that have a unique identifier property, you should track by this identifier instead of the object instance, e.g. item in items track by item.id. Should you reload your data later, ngRepeat will not have to rebuild the DOM elements for items it has already rendered, even if the JavaScript objects in the collection have been substituted for new ones. For large collections, this significantly improves rendering performance.
— AngularJS ng-repeat API Reference
Just replace your result with result.Table in your controller because if you properly see your response it is inside "Table" named array. Try this you should be able to see your records
SMSApp.controller('studentController', function ($scope, GetStudentService) {
$scope.msg = "Welcome from Controller";
GetStudentService.getAll().then(function (result) {
$scope.school = result.Table;
console.log(result);
});
});
Note: I have replaced your API call in the jsfiddle link with the response mentioned in the question.
JSFiddle Link : http://jsfiddle.net/zu8q7go6/9/
I want to pass ASP.NET MVC view (.cshtml) values to angular js controller. I am familiar with Angular js, But not on MVC. I have values in MVC cshtml. I want to pass that value to my angular controller. Please provide me some info or demo project or link which explains in detail.
i want somthing like below,
Get value from mvc model and pass it to cshtml.
from cshtml pass value to angular js controller and display in angular html page
I do not want to use cshtml as my view. I want to get data from cshtml to angular controller and display in seperate html
Using the very first tutorial I pulled up I grabbed this snippet:
var AwesomeAngularMVCApp = angular.module('AwesomeAngularMVCApp', ['ngRoute']);
AwesomeAngularMVCApp.controller('HomeController', HomeController);
var configFunction = function ($routeProvider) {
$routeProvider.
when('/Listings', {
url: 'routesDemo/one'
})
.when('/Listing', {
url: 'routesDemo/two'
})
.when('/Listings', {
url: 'routesDemo/three'
});
}
configFunction.$inject = ['$routeProvider'];
AwesomeAngularMVCApp.config(configFunction);
Now this how you link a view to a controller action in MVC:
using System.Web.Mvc;
namespace AwesomeAngularMVCApp.Controllers
{
public class RoutesDemoController : Controller
{
public ActionResult One(string title)
{
var listings = db.Articles.Contain(title);
return PartialView(listings, "..\Views\Shared\WhateverPartialView.cshtml");
}
[HttpPost]
public async Task<ActionResult> Two(Article article)
{
if(ModelState.isValid){
_db.Add(article)
}
return View(article); //This one returns entire page
}
public JsonResult Three(string title)
{
var listing = db.Articles.Where(t => t.Title == title).SingleOrDefault();
return Json(listing, JsonRequestBehavior.AllowGet);
}
}
}
These partial views would be in the Views folder in a sub folder RoutesDemo
one.cshtml GET
two.cshtml POST ie: a href="#/Article/6" type=submit" class="btn"
$("form").submit( function(){
$.ajax( function(url, data){
});
});
three.cshtml GET ie
$.ajax({
url: '#Url.Action("routeDemo", "three")',
//url: baseUrl + url,
data: {
search: searchBlue.val()
},
success: function (data) {
$("#msg").html("Results for" + searchBlue.val());
searchBlue.searchMeme({ searchComplete: true });
$('#main').fadeOut(800, function () {
$('#main').html("" + data + "").fadeIn().delay(800);
});
searchBlue.val("");
},
error: function (xhr, status, error) {
alert(error);
}
});
If you want to pass values to the angular controller use razor syntax and bind the value to the html input. The top of the view file will make it so angular knows what type of object to expect.
IE: Top of Two.cshtml
#model AwesomeAngularMVCApp.Article
That should be it besides route.config for angular
If you want to handle the Model object using razor syntax check out this tutorial. Pretty cut and dry.If that is not enough I will show example of binding #Model.attribute/property to an html element after work tomorrow
EDIT
<div class="row-fluid" ng-controller="PersonDetailsController" ng-init="personId=#Model.Id">
Angular injects it in the scope during initialization, so you can refer to it as $scope.personId
I have values that I want to edit in an other page
<tr ng-repeat="facilitator in listFacilitators" ng-click="showDetails(facilitator);goToFacilitatorP()">
<td>{{facilitator.username}}</td>
<td><li><ul>{{facilitator.cwsessionsAnime}}</ul></li></td>
<td><li><ul>{{facilitator.profilFollow}}</ul></li></td>
</tr>
when I click on I'm supposing to be redirected in another page to show the details and edit them , so I tried to do this in the controller:
$scope.showDetails= function(facilitator){
$scope.selectedFac= facilitator;
}
and in the second page, I do this:
<tr>
<td> {{selectedFac.username}}</td>
<td> {{selectedFac.lastname}}</td>
<td> {{selectedFac.firstname}}</td>
<td> {{selectedFac.title}}</td>
</tr>
it works in the same page but not when I'm redirected, can you help me please?
UPDATE:
I do this but I still haven't data in the seconde page:
1- In the first controller for the 1 page I declared:
profilCtrl.controller('ProfilCtrl', [ '$scope','$location', 'profilService', 'facilitatorPService', function($scope,$location, profilService, facilitatorPService) {
/* ---- appel a facilitator Service ---- */
var facilitator = '';// What ever this is set to in the first place
facilitatorPService.facilitator = facilitator;
2- In my 2nd controller (for the second in where I want to show the details) , I have declared:
facilitatorPCtrl.controller('facilitatorPCtrl', [ '$scope','$rootScope','$cookieStore','$location','membreService','facilitatorPService','userService',function($scope,$rootScope,$cookieStore,$location, membreService,facilitatorPService, userService) {
facilitatorPservice.editFacil= function($scope){
$scope.showDetails = function(){
$scope.selectedFac = facilitatorPService.facilitator;
}
};
3- Ans in my service facilitatorPService I have this:
facilitatorPService.factory('facilitatorPService', [ '$resource','$http', function($resource,$http) {
var service = {
getAllFacilitators : function($scope){
return $resource('/gari-web/services/facilitators/AllFacilitators', {}, {
query : {
method : 'GET', isArray:true,
}}
});
},
editFacil: function($scope){
var self= this;
self.facilitator={};
}};
return service;
} ]);
4- in My html page I put this:
<td>{{selectedFac.username}}</td>
Can someone please tell me what I did wrong, I don't find the mistake
Controllers are 'flushed' when you change views. To keep data from a view to another, store your data within a Service.
UPDATE
.service('FacilitatorService', [
function() {
var self = this;
self.facilitator = {};
}
])
Then in your controllers, inject yourself the service you just created.
.controller('FirstController', ['FacilitatorService',
function(FacilitatorService) {
var facilitator = '';// What ever this is set to in the first place
FacilitatorService.facilitator = facilitator;
}
])
And in your second controller
.controller('SecondController', ['FacilitatorService', '$scope',
function(FacilitatorService, $scope) {
$scope.showDetails = function(){
$scope.selectedFac = FacilitatorService.facilitator;
}
}
])
Like this, your FacilitatorService.facilitator data will be accesible in all your controllers that use FacilitatorService
I recommend using ui router, this resolve two problems, the view change and the data share.
Read more about router ui
doc http://angular-ui.github.io/ui-router/site/#/api/ui.router
The current state
$stateProvider
.state('current', {
url: "/curent",
templateUrl: 'current.html',
controller: 'currentCtrl'
})
Then you can choose how change the view and share the data, the first is the controller, the second is html. Only use one
From current controller (option 1)
$scope.showDetails= function(facilitator){
$state.go('togo', {myCurrentdata: facilitator}) ;
}
From current html (option2)
<tr ng-repeat="facilitator in listFacilitators" ui-sref="togo({myCurrentdata : facilitator})">
<td>{{facilitator.username}}</td>
<td><li><ul>{{facilitator.cwsessionsAnime}}</ul></li></td>
<td><li><ul>{{facilitator.profilFollow}}</ul></li></td>
</tr>
The state that you want to go
$stateProvider
.state('togo', {
url: "/togo",
templateUrl: 'togo.html',
controller: 'togoCtrl'
param: {myCurrentdata: null}
})
To go controller
if($stateParams.myCurrentdata){
$scope.selectedFac = $stateParams.myCurrentdata
}
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>
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;
})
}]
}
}