Data from Angular .then function is not displayed on page - javascript

I have this code in my stucontrollers.j
/// <reference path="../angular.js" />
var stucontrollers = angular.module("stucontrollers", []);
stucontrollers.controller("GetStudentsList",
function GetStudentsList($scope, $http) {
$http({
method: 'GET',
url: '/api/students'
}).then(function(data) {
$scope.students = data;
});
});
and in my view, I have this
<div ng-app="StudentApp">
<div ng-controller="GetStudentsList">
<table>
<thead>
<tr>
<th>Id</th>
<th>FistName</th>
<th>LastName</th>
<th>Age</th>
<th>Gender </th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in students">
<td>{{item.Id}}</td>
<td>{{item.FirstName}}</td>
<td>{{item.LastName}}</td>
<td>{{item.Age}}</td>
<td>{{item.Gender}}</td>
</tr>
</tbody>
</table>
</div>
</div>
and in my app.js this is what I have
/// <reference path="../angular.js" />
var module = angular.module("StudentApp", ["stucontrollers"]);
This is in my StudentsController.cs
// GET: api/Students
public IQueryable<Student> GetStudents()
{
return db.Students;
}
I am trying to get the list of the students into my view but I am only able to get it in the response of the page inspector not on the page itself. What am I doing wrong. Thank you.
EDIT
Now I am able to see my data in the console. But I still couldn't see it in my page. Below is the data I get in the console.
data
:
Array(2)
0
:
{Id: 1, FirstName: "Juan", LastName: "Dela Cruz", Age: 25, Gender: "Male"}
1
:
{Id: 2, FirstName: "Maria ", LastName: "Makiling", Age: 30, Gender: "Female"}

Try to call $scope.$apply() after setting the value.
$http({
method: 'GET',
url: '/api/students'
}).then(function(data) {
$scope.students = data;
$scope.$apply();
});
or simply
$http({
method: 'GET',
url: '/api/students'
}).then(function(data) {
$scope.$apply(function() {
$scope.students = data;
});
});
From the $apply documentation
$apply() is used to execute an expression in AngularJS from outside of the AngularJS framework.

To debug this, try setting value of $scope.students directly, like this:
/// <reference path="../angular.js" />
var stucontrollers = angular.module("stucontrollers", []);
stucontrollers.controller("GetStudentsList",
function GetStudentsList($scope, $http) {
$scope.students = [{Id: 1, FirstName: "John"}];
});
Then either one of two things happens:
a) You see John in the list: this means ng-controller and ng-repeat work. Problem in in fetching the data. Try next by console.logging your response.
b) You don't see John in the list: There is something wrong even before the request happens.

This worked for me, You might as well try it :
/// <reference path="../angular.js" />
var stucontrollers = angular.module("stucontrollers", []);
stucontrollers.controller("GetStudentsList",
function GetStudentsList($scope, $http,$rootScope) {
$http({
method: 'GET',
url: '/api/students'
}).then(function(data) {
$rootScope.$apply(function(){
$scope.students = data;
});
});
});

Try this:
/// <reference path="../angular.js" />
var stucontrollers = angular.module("stucontrollers", []);
stucontrollers.controller("GetStudentsList",
function GetStudentsList($scope, $http) {
$http({
method: 'GET',
url: '/api/students'
}).then(function(response) {
$scope.students = response.data;
});
});

Related

How to get $scope.someStuff response values into variable?

This is my angular controller:
angular
.module('hameedApp', [])
.controller('hameedController', function($scope, $http) {
$http({
method: 'GET',
url: 'json.php'
}).then(function(response) {
$scope.contacts = response.data;
}).catch(function(response) {
console.log('error');
})
});
This is my html from body tag:
<table class="table">
<tr>
<th>Name</th>
<th>Phone No</th>
<th>Email</th>
</tr>
<tr ng-repeat="contact in contacts">
<td>{{contact.name}}</td>
<td>{{contact.gsm}}</td>
<td>{{contact.email}}</td>
</tr>
</table>
<script>
var test = {{contacts}}
console.log(test);
</script>
I want to get above {{contacts}} full array json data in one variable called "test".
is it possible?
Angular concept is anything you put in $scope is not directly accessible in non-angular code. What you can do is, you can assign it to any global variable using window object like below.
angular
.module('hameedApp', [])
.controller('hameedController', function($scope, $http) {
$http({
method: 'GET',
url: 'json.php'
}).then(function(response) {
$scope.contacts = response.data;
window.contacts = response.data;
}).catch(function(response) {
console.log('error');
})
});
Now you can access that contacts anywhere in angular as well as non-angular code.
Edited
As you want to get the contacts in non-angular code, you have to use callback mechanism to tell your non-angular code about updated value. See below
In you <head>, add a new method in window like this
<head>
<script>
....
....
window.updateContacts = function(contacts) {
console.log(contacts);
}
....
....
</script>
</head>
Now you can use this callback from angular code, like below
angular
.module('hameedApp', [])
.controller('hameedController', function($scope, $http) {
$http({
method: 'GET',
url: 'json.php'
}).then(function(response) {
$scope.contacts = response.data;
window.updateContacts(response.data);
}).catch(function(response) {
console.log('error');
})
});

No Action in angular js

Below is my code
<script>
var app = angular.module("myApp2", [])
app.controller("ShowController", ['$scope', function ($http) {
$scope.Get = function () {
var adata = { EmpId: 'EmpId' };
var JSon = JSON.stringify(adata);
EmpId = $("#EmpIdb").val();
$http({
method: "Get",
url: servUrl + "Show",
data: JSon,
}).then(function mySucces(response) {
alert(response.data);
}, function myError(error) {
alert(response.statusText);
});
}
}])
</script>
</title>
</head>
<body ng-app="myApp2" ng-controller="ShowController">
<center>
<h3> Please Enter Your Emp Id</h3></br>
<input type ="text" id="EmpIdb" /></br>
<input type="button" id ="Fetch" value="Fetch Details" ng-click="Get();"/>
<div ng-view></div>
</center>
which is not working.
There is no error in the console and I am not able to debug it either.
Any help welcomed
There are multiple problems. But I do not really get why error is not coming
1 . Where is the servUrl coming from?
2 .
$http({
method: "Get",
url: servUrl + "Show",
data: JSon,
})
to
$http({
method: "GET",
url: servUrl + "Show",
data: JSon,
})
3 . Change this in 3rd line
app.controller("ShowController", ['$scope', function ($http) {
to
app.controller("ShowController", ['$scope', '$http', function ( $scope, $http) {
Fix these. then try again.
EDITED
DEMO Plunker with working code.
Change your code like below. You are not passing scope in controller function.
<script>
var app = angular.module("myApp2", [])
app.controller("ShowController", ['$scope', '$http', function ($scope, $http) {
$scope.Get = function () {
var adata = { EmpId: 'EmpId' };
var JSon = JSON.stringify(adata);
EmpId = $("#EmpIdb").val();
$http({
method: "GET",
url: servUrl + "Show",
data: JSon,
}).then(function mySucces(response) {
alert(response.data);
}, function myError(error) {
alert(response.statusText);
});
}
}])
</script>
Try this. just inject $scope and $http in your controller
var app = angular.module("myApp2", [])
app.controller("ShowController", ['$http', '$scope', function ($http, $scope) {
$scope.Get = function () {
var adata = { EmpId: 'EmpId' };
var JSon = JSON.stringify(adata);
EmpId = $("#EmpIdb").val();
$http({
method: "Get",
url: servUrl + "Show",
data: JSon,
}).then(function mySucces(response) {
alert(response.data);
}, function myError(error) {
alert(response.statusText);
});
}
}])

How to pass the javascript object from view to controller using angular JS?

I have tried to pass the customer class object to Asp.net MVC controller using angularJS $http service.
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope,$http)
{
$scope.getRecord = function () {
$scope.objCustomer = { Id: 5, Name: 'sasi', Dept: 'IT' };
$http({ url: "Home/GetCustbyID",
method: "GET",
params: {objCustomer: $scope.objCustomer} })
.then(function (response)
{
//success code
};});
}});
Controller Action is defined like:
public JsonResult GetCustbyID(Customer objCustomer)
{
return Json(objCustomer, JsonRequestBehavior.AllowGet);
}
However in the above controller action customer object is always passed as null. Did i miss anything?
Please help me guys to resolve this.
You should use a POST request if you wish to send multiple parameters at once in a JSON object in your AJAX request and capture that as an Object on your server side.
$http.post(url, $scope.objCustomer)
.then(successCallback, errorCallback);
As you are actually sending data to server you are posting in $http.
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope,$http)
{
$scope.getRecord = function () {
$scope.objCustomer = { Id: 5, Name: 'sasi', Dept: 'IT' };
$http({
url: "Home/GetCustbyID",
method: "POST",
data: $.param({ objCustomer : $scope.objCustomer })
})
.then(function(response) {
//success code
};});
}});
in other case if you like to send/pass data as json string you will have to use stringify like this
var data = $.param({
json: JSON.stringify({
name: $scope.name
})
});
$http.post("/path_of_controller", data).success(function(data, status) {
//do whatever you like
})

Update model in ng-repeat when is self-updated

I've got an array in my scope and I am iterating over each element with an input in the html template:
Controller:
app.controller("otherArticleCtrl", ["$scope", "$http", function($scope, $http) {
$scope.articles = [{ url: 'index.php', title: "First"}, { url: 'index.php', title: "Second"}];
}]);
Template:
<div ng-repeat="(key, article) in articles track by $index">
<h1>{{ article.title }}</h1>
<input type="text" ng-model="article.url"/>
</div>
I need when user modifies the url in the input, make an AJAX get call, and update the article title.
I've made a watch function looping through the array:
for(var i=0; i < $scope.articles.length; i++) {
$scope.$watch('articles['+i+'].url', function(new, old){
if(new != old){
$http({
method: 'GET',
url: new
}).then(function successCallback(response) {
$scope.articles[i].title = response.title;
});
}
}, true);
}
But $scope.articles[i] is undefined and I don't know how to get the reference of the model or element that is changed.
Any ideas? Thanks for help.
Should not use $watch in any loop. In this case you can use ng-change instead of $watch. and send index number in ng-change function. like ng-change="changeUrl($index)". and function shown in bellow.
can try:
In html:
<div ng-repeat="(key, article) in articles track by $index">
<h1>{{ article.title }}</h1>
<input type="text" ng-model="article.url" ng-change="changeUrl($index)"/>
</div>{{index}}
In controller:
$scope.articles = [{ url: 'index.php', title: "First"}, { url: 'index.php', title: "Second"}];
$scope.changeUrl = function(index){
$http({
method: 'GET',
url: $scope.articles[index].url
}).then(function successCallback(response) {
$scope.articles[index].title = response.title;
});
};
you can use $http.get
$http.get($scope.articles[index].url)
.then(function(response) {
$scope.articles[index].title = response.title;
});
I'd suggest using ngChange instead.
You can do something like this :
<input type="text" ng-model="article.url" ng-change="somethingChanged()"/>
And add the function inside your controller. If you need to know the index of the element that changed you can use $index from the ng-repeat to know where is the data that changed :
<input type="text" ng-model="article.url" ng-change="somethingChanged($index)"/>
$scope.somethingChanged = function(index) {
$scope.articles[index]; <--------- Here is the element that changed
}
Happy coding!

AngularJS: Call httpget on value change from textbox

I have a web service which returns json file on call with a parameter for the id of an entry. I have a angular method that returns the data returned from that method. I have no idea how to recall the service when the input of the id has changed as I want to recall that method when a new value has been supplied.
The parameter that I pass in for the Id is called Reference. The HTML returns object with a reference of 1234 but if I change the value I dont know how to recall the service.
This is what I have so far:
Angular:
var app = angular.module("myModule", [])
.controller("myController", function ($scope, $http) {
var res = $http({
method: 'GET',
url: 'AirPortrWebService.asmx/DashboardDetail',
params: { Reference : '1234' }
})
.then(function (response) {
$scope.booking = response.data
});
$scope.test = "Angular Method Called";
$scope.Reference = '1234';
});
Html
<!DOCTYPE html>
<html>
<head>
<script src="scripts/angular.js"></script>
<script src="app/NewAppTwo.js"></script>
</head>
<body ng-app="myModule" ng-controller="myController">
{{test}}
{{Reference}}
<br />
<br />
<input type="text" ng-model="Reference" ng-change="booking"/>
{{booking}}
</body>
</html>
Change ng-change="booking" to a function that is called everytime that models Refences changes:
$scope.getReference = function(referenceNumber){
$http({
method: 'GET',
url: 'AirPortrWebService.asmx/DashboardDetail',
params: { Reference : referenceNumber}
}).function (response) {
$scope.booking = response.data
});
}
<input type="text" ng-model="Reference" ng-change="getReference(Reference)"/>
try this :
var app = angular.module("myModule", [])
.controller("myController", function ($scope, $http) {
$scope.refresh = function(){
var res = $http({
method: 'GET',
url: 'AirPortrWebService.asmx/DashboardDetail',
params: { Reference : $scope.Reference }
})
.then(function (response) {
$scope.booking = response.data
});
}
$scope.test = "Angular Method Called";
$scope.Reference = '1234';
});
and html
<input type="text" ng-model="Reference" ng-change="refresh()"/>
ng-change call the given function each time the input change.
refresh() don't need a parameter because it use $scope.Reference

Categories