I am new to AngularJS and need to use AngularJs to render my MVC controller Json output. Below is my MVC Controller that output Json:
[HttpGet]
public JsonResult GetAllData()
{
int Count = 50;
return Json(Workflow.Teacher.GetTeachers(Count), JsonRequestBehavior.AllowGet);
}
My Angular Controller that calls the GetAllData Action method:
angular.module('myFormApp', [])
.controller('HomeController', function ($scope, $http, $location, $window) {
$scope.teacherModel = {};
$scope.message = '';
$scope.result = "color-default";
$scope.isViewLoading = false;
$scope.ListTeachers = null;
getallData();
//******=========Get All Teachers=========******
function getallData() {
$http({
method: 'GET',
url: '/Home/GetAllData'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
$scope.ListTeachers = response;
console.log($scope.ListTeachers);
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.errors = [];
$scope.message = 'Unexpected Error while saving data!!';
console.log($scope.message);
});
};
})
.config(function ($locationProvider) {
$locationProvider.html5Mode(true);
});
Further my MVC layout markup is bellow:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Teachers List</h2>
<div id="content" ng-controller="HomeController">
<span ng-show="isViewLoading" class="viewLoading">
<img src="~/Content/images/ng-loader.gif" /> loading...
</span>
<div ng-class="result">{{message}}</div>
<table class="table table-striped">
<tr ng-repeat="teacherModel in ListTeachers">
<td>{{teacherModel.TeacherNo}}</td>
<td>{{teacherModel.TeaFName}}</td>
<td>{{teacherModel.TeaSName}}</td>
</tr>
</table>
</div>
#section JavaScript{
<script src="~/Scripts/angular.js"></script>
<script src="~/ScriptsNg/HomeController.js"></script>
}
further to above my main layout's body tag also have ng-app
<body ng-app="myFormApp" >
I am using MVC version 5 with AngularJs v1.6.4.
On debugging I can confirm that it does call getallData() actionMethod and does return rows in Json. I am not getting any error but its not rendering the model values either.
Any suggestions would be appreciated.
use response.data to catch the data.
change
$scope.ListTeachers = response;
to this
$scope.ListTeachers = response.data;
You have a number of problems with this code. Firstly, by assigning
$scope.ListTeachers = null;
you are making it more complicated to work with this variable later. If you expect REST interface to return you an array, then it is fine to make initial assignment as an empty array.
$scope.ListTeachers = [];
It is important because you should not override this object when you get a new result back. Angular adds its own magic to objects it is bound to, and by overriding an object you destroy that magic.
How you should update the data is something like this this:
then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
$scope.ListTeachers.length = 0;
if( response && response.data){
response.data.forEach(function callback(currentValue)
{
$scope.ListTeachers.push(currentValue);
});
}
console.log($scope.ListTeachers);
}
I hope this helps.
Then callback response has several parameters like data , headers, status , statustext to check your request.
Related
Trying to make ajax request when searched data is not found in object.
Html:-
Search programming languages: <input type="Text" ng-model="out.pl">
<div ng-controller="MyContRollEr">
<table border="2">
<tr>
<td>Programming Language:</td>
<td>Percentage:</td>
<td>Salary:</td>
<td>People:</td>
<td>Started Date:</td>
</tr>
<tr ng-repeat="data in info | filter:out">
<td>{{data.pl}}</td>
<td>{{data.percent}}</td>
<td>{{data.salary |currency:'Rs.'}}</td>
<td>{{data.people | number :2}}</td>
<td>{{data.date | date:"yyyy/MM/dd"}}</td>
</tr>
</table>
Controller:-
var app = angular.module('app',[]);
app.controller('MyContRollEr',function($scope) {
var info = [
{pl:'php',percent:'10%',salary:10000000,people:234524},
{pl:'Java',percent:'20%',salary:9822200,people:234443},
{pl:'python',percent:'10%',salary:8739300000,people:2345521)},
];
$scope.info = info;
});
My Function :-
function sendRequest(){
$http({
method:'POST',
url:'index.php',
data:{search:'data'}
}).then(function(data) {
$scope.out = data;
})
}
How to do this combining my controller, function and model.
,This is where angular service comes into play. You should make a new file for both controllers and services. For the sake of simplicity though, you can just add the following code into your current file AFTER the controller.
app.service('myService',function($http) {
this.sendRequest = function() {
$http({
method:'POST',
url:'index.php',
data:{search:'data'}
}).then(function (response) {
console.log(response);
return response.data; // Most APIs have the "data" in the response object. But you can take this out if the console log doesn't show that key in the object.
})
}
)
Once that is done, you'll inject your service into your controller here:
app.controller('MyContRollEr',function($scope, myService) { // Notice that the service is a parameter in controller now.
Next, lets call do the POST by hitting the service. Inside of your controller block, write the following:
myService.sendRequest().then(function (response) {
console.log(response);
})
If you aren't using Gulp (or something similar), then you will need to add the service into your index.html(Or whatever file is your base html file) file just like you did(I assume) with your controller.
Let me know if you have any questions!
what I'm trying to do is a function in javascript that sends a simple data to a laravel controller and then upload it to the database, the problem I have is that until now I have not been able to find a way to send this data, always I get error 500.
Laravel Controller:
public function crearRegistro(Request $request){
$registro = new Registro();
$registro->indicador = $request->indicador;
$registro->save();
}
Javasript Function:
$scope.calculoIndicador = function(){
$http.post("/calculoIndicador")
.then(function(response) {
});
$scope.indicador = 5 +5;
alert('Se ha guardado correctamente');
}
view:
<input class="btn btn-success" style="" ng-click="calculoIndicador()"
type="submit" value="Enviar"/>
Route:
Route::post('/calculoIndicador', 'TecnologiaController#crearRegistro');
(First, sorry with my bad english)
I assume that you use Laravel 5.6. On controller you have to use:
$request->all() method to get the data passed to controller via post on javascript. On your code i assume yout want the "indicador", so:
$requestData = $request->all();
$registro->indicador = $requestData['indicador'];
But on your javascript you have to pass "indicador" as parameter on post request data. So, on javascript (or typescript of Angular) post do something like this:
$http.post("/calculoIndicador", {indicador: 'your_data'}).then(
function(response) {
$scope.status = response.status;
$scope.data = response.data;
}, function(response) {
$scope.data = response.data || 'Request failed';
$scope.status = response.status;
}
)
Can you update this page with stack trace of this error?
i'm trying to move to my account.html from my login.html, using javascript, where i in login.html there will be a validation from MongoDB. And if it's the same data, it was supposed to go to acoount.html, but it doesn't. This is my javascript:
.controller('LoginCtrl', function($scope, $state, $ionicPopup, AuthService) {
$scope.data = {};
$scope.login = function(data) {
var formdata = {
num : $("#num").val(),
pw : $("#pw").val()
};
var Jformdata = JSON.stringify(formdata);
//var url = $location.url();
console.log(Jformdata);
$.ajax({
url : "/ProjectSinarmas/submit",
context : document.body,
type : 'POST',
data : Jformdata,
contentType : "application/json"
}).done(function (response){
//console.log(response);
if(response == "true"){
//$state.go('main.account');
var path = $location.path("http://localhost:8089/ProjectSinarmas/templates/account.html");
alert("Login Success");
}else{
$scope.showAlert('Nomer Telephone dan PIN Salah');
}
});
};
I got this error response from my html:
controllers.js:53 Uncaught ReferenceError: $location is not defined
Thanks before, and have a nice day.
You need to call $location in Controller check below
.controller('LoginCtrl', function($scope, $state,$location, $ionicPopup, AuthService) {
//code........
}
In addition to adding $location to your controller, my guess is you might also need to use the AngularJS $http method (or $post) method instead of $ajax, so that AngularJS knows when your request is completed and handles the scope update.
also change:
var path = $location.path("http://localhost:8089/ProjectSinarmas/templates/account.html");
to:
$location.path("http://localhost:8089/ProjectSinarmas/templates/account.html");
no need to put in the path var if its not used.
I am merely trying to populate an array from an $http request and display the results in a table. Using Firebug, it seems to me that the data is being retrieved properly. See pictures for results.
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('ContactsController', function ($scope, $http)
{ var self = this; //added after initial post.
this.contactList = [];
this.InitiateContactList = function(arrayContacts) //this.InitiateContactList doesn't work?
{ for(i = 0; i < arrayContacts.length; i++)
this.contactList.push(arrayContacts[i]);
};
$http({
method: 'GET',
url: 'someurl', //pseudoCode
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response)
{ if(angular.isArray(response.data))
{ //this.contactList = response.data; //is this working properly?
self.contactList = angular.fromJson(response.data);
//this.InitiateContactList(response.data);
}
}, function errorCallback(response) {
});
});
app.controller('ActionsController', function ($scope, $http)
{
});
</script>
</head>
<body ng-controller="ActionsController as ActCtrl">
<div ng-controller="ContactsController as ContactsCtrl">
<table
<tr><th Email</th>
<th>Name</th>
<th>Frequency</th></tr>
</table>
<div ng-repeat="Contact in ContactsCtrl.contactList">
<table >
<tr><td>{{Contact.Email}}</td><td>test name</td><td>{{Contact.Frequency}}</td></tr>
</table>
</div>
</div>
</body>
</html>
this.contactList = angular.fromJson(response.data); seems to be working. The DOM array is populated as expected, but the ng-repeat doesn't seem to be working. I've done this procedure a couple other times in other contexts and it has worked as expected. What am I missing?
Update: The Batarang extension in Chrome shows the following:
Is it normal to have the index 'Contact' showing like that?
In your ContactsController, do this
var self = this;
Now use self instead of all this in your controller:
$http({
method: 'GET',
url: 'someurl', //pseudoCode
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
self.contactList = angular.fromJson(response.data);
});
Hope that helps.
this.contactList = angular.fromJson(response.data);
In this instance, this refers to the function prototype of the anonymous callback function from the then() call. Be careful in Javascript when using the word this in many callbacks and such. Declare a variable, and assign the needed function prototype, and then reference that variable, instead of the reserved, ever-changing this keyword.
I am attempting to make a simple authentication service by sending a Post to a php file, I need it to load the home page partial on my ng-view when its successful.
This is what I tried :
function loginCtrl($scope, $http, $location){
$http.post(url,data).success(function(data){
$location.path('/home');
});
}
Results in my url changing but ng-view not updating. It updates when I manually refresh the page.
(routes have been configured properly at the $routeProvider, I have tested redirecting this with a standalone function not as a callback and it works )
I have also tried defining $location.path('/home') as a function and then calling it on the callback it still doesn't work.
I did some research and found some articles stating this happens when using another third party plugin, I am only loading angular.js
Any insights or pointers to some study material will be great
Here is the changeLocation example from this article http://www.yearofmoo.com/2012/10/more-angularjs-magic-to-supercharge-your-webapp.html#apply-digest-and-phase
//be sure to inject $scope and $location
var changeLocation = function(url, forceReload) {
$scope = $scope || angular.element(document).scope();
if(forceReload || $scope.$$phase) {
window.location = url;
}
else {
//only use this if you want to replace the history stack
//$location.path(url).replace();
//this this if you want to change the URL and add it to the history stack
$location.path(url);
$scope.$apply();
}
};
There is simple answer in the official guide:
What does it not do?
It does not cause a full page reload when the browser URL is changed.
To reload the page after changing the URL, use the lower-level API,
$window.location.href.
Source: https://docs.angularjs.org/guide/$location
I am doing the below for page redirection(from login to home page). I have to pass the user object also to the home page. so, i am using windows localstorage.
$http({
url:'/login/user',
method : 'POST',
headers: {
'Content-Type': 'application/json'
},
data: userData
}).success(function(loginDetails){
$scope.updLoginDetails = loginDetails;
if($scope.updLoginDetails.successful == true)
{
loginDetails.custId = $scope.updLoginDetails.customerDetails.cust_ID;
loginDetails.userName = $scope.updLoginDetails.customerDetails.cust_NM;
window.localStorage.setItem("loginDetails", JSON.stringify(loginDetails));
$window.location='/login/homepage';
}
else
alert('No access available.');
}).error(function(err,status){
alert('No access available.');
});
And it worked for me.
Instead of using success, I change it to then and it works.
here is the code:
lgrg.controller('login', function($scope, $window, $http) {
$scope.loginUser = {};
$scope.submitForm = function() {
$scope.errorInfo = null
$http({
method : 'POST',
url : '/login',
headers : {'Content-Type': 'application/json'}
data: $scope.loginUser
}).then(function(data) {
if (!data.status) {
$scope.errorInfo = data.info
} else {
//page jump
$window.location.href = '/admin';
}
});
};
});
Use : $window.location.href = '/Home.html';
it's very easy code .. but hard to fined..
detailsApp.controller("SchoolCtrl", function ($scope, $location) {
$scope.addSchool = function () {
location.href='/ManageSchool/TeacherProfile?ID=' + $scope.TeacherID;
}
});