Moving to other html through javascript - javascript

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.

Related

AngularJs not rendering value

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.

Angular add mock JSON Data

I'm new to angular and buildig an application that reads data from a API and renders it in an HTML table. For the moment I m trying to see how I can manipulate the table data and thereby changing the model (JSON). I understand this would need API support to make those changes, but for the moment I'd like to try this with mock data inside the Javascript.
Can you please look into this Fiddle code and tell me how I can do that ?
(function() {
var app = angular.module('myApp', []);
app.controller('PeopleController', function($scope, $http) {
$http({
url: "https://api.myjson.com/bins/584d5",
method: "GET"
}).success(function(data,status) {
$scope.people = data.people;
});
});
})();
Thanks
Code Pen Link
So you'd like to change the JSON? you can try a PUT.
Here's your codepen modified: http://codepen.io/anon/pen/qZRYxZ?editors=1010
$scope.myData = {"people":[{"personName":"Scott Walker","personAge":"43","dateOfBirth":"09-12-1972","location":"Leeds","gender":"male"},{"personName":"Paula Lamb","personAge":"38","dateOfBirth":"02-01-1978","location":"Alberta","gender":"female"},{"personName":"Jonathan Joestar","personAge":"22","dateOfBirth":"02-28-1850","location":"UK","gender":"male"}]};
$http.put('https://api.myjson.com/bins/584d5', $scope.myData)
.success(function (data) {
// alert("success!");
});
Created a plunker for you. Basically you can just call the http request to the place where the json file is located. So in this case it is just root, but if it is in a map, just follow the path relative from index.
$http({
url: "example.json",
method: "GET"
}).success(function(data, status) {
console.log($scope.people);
$scope.people = data.people;
});
https://plnkr.co/edit/LmoRco8FN4Ck8xZ7bM2x

How can i post the ngCart checkout button on http using php and angular js?

I do not know how can i post my data's into a new php page and this is my code:
<ngcart-checkout service="http" settings="{ url:'./checkout.php' }">Checkout </ngcart-checkout>
but the original code from the ngCart docs is
<ngcart-checkout service="http" settings="{ url:'/checkout' }"></ngcart-checkout>
the ngcart-checkout code is
<button class="btn btn-primary" ng-click="checkout()" ng-disabled="!ngCart.getTotalItems()" ng-transclude>Checkout</button>
still it does not redirect me unto checkout.php and so i go to the ngcart.js and the codes for the checkout using http post is
.service('ngCart.fulfilment.http', ['$http', 'ngCart', function($http, ngCart){
this.checkout = function(settings){
return $http.post(settings.url,
{data:ngCart.toObject()})
}
}])
so again my problem was how can i redirect my checkout button unto the checkout.php and how can i post those items unto the checkout.php using http post?
I think perhaps you are looking for something like this in your ngcart.js file
<script>
.service('ngCart.fulfilment.log', ['$http', 'ngCart', function($http, ngCart){
this.checkout = function(settings){
//var item_data = ngCart['$cart']['items'], message;
//return $http.post('checkout.php',
// {data:item_data});
var postData = 'item_data='+JSON.stringify(ngCart['$cart']['items']);
$http({
method : 'POST',
url : 'checkout.php',
data: postData,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(res){
console.log(res);
}).error(function(error){
console.log(error);
});
}
}])</script>

Thinking in AngularJS - what's the proper approach for modifying the DOM in an AJAX request?

I'm brand new to AngularJS. I've read over "Thinking in AngularJS" if I have a jQuery background? and the answers made a lot of sense. However, I'm still having a hard time translating what I want to do without relying on jQuery.
My request seems fairly simple. I have a form that does an AJAX call when submitted. I want the Submit button to visually update to inform the user on the the AJAX request status. The Submit button won't be updated with simple text, but instead be updated with text plus a icon. The icon is in HTML which means I can't use AngularJS simple data binding.
I have this request working in jsFiddle.
HTML
<div ng-app >
<form id="id_request" ng-controller="RequestCtrl">
<input id="id_title" name="title" ng-model="request.title" type="text" class="ng-valid ng-dirty" />
<button type="submit" class="btn btn-primary" ng-click="submitRequest($event)">
Submit
</button>
</form>
</div>
AngularJS
function RequestCtrl($scope, $http) {
$scope.request = {};
$scope.submitRequest = function($event) {
$($event.target).prop("disabled", true).html('<i class="icon-refresh icon-spin"></i> Submitting</a>');
$http({
method : 'GET',
url : '/ravishi/urSDM/3/',
data : $.param($scope.request),
headers : {
'Content-Type' : 'application/x-www-form-urlencoded',
}
}).
success(function(data, status, headers, config) {
console.log("success");
console.log($event);
// This callback will be called asynchronously when the response is available.
$($event.target).html('<i class="icon-ok"></i> Success').delay(1500).queue(function(next) {
$(this).removeAttr("disabled").html("Submit");
next();
});
}).
error(function(data, status, headers, config) {
console.log("error");
// Called asynchronously if an error occurs or server returns response with an error status.
$($event.target).html('<i class="icon-warning-sign"></i> Error').delay(1500).queue(function(next) {
$(this).removeAttr("disabled").html("Submit");
next();
});
});
}
}
I am completely aware that this is the wrong way to do it in AngularJS. I shouldn't be updating the DOM in my controller and I should by trying to avoid jQuery completely.
From what I gather, I need to use directives. I've seen some examples but can't think of a nice way to update the button's HTML through the multiple states it goes through. There are four states of the button:
1 Initial -> 2 Submitting -> 3 Error or 4 Success -> 1 Initial
My first thought is to update an arbitrary button attribute in the controller. Then in the directive, I would somehow retrieve the attribute value and conditionally update the HTML appropriately. With this approach, I am still unsure of how to link the status of the AJAX request to the button's HTML in the directive. Should I forgo the AJAX call in the controller and instead do the AJAX call in the directive by binding to the button's click event? Or, is there is a better way to do this?
The main change you have to do is to move away from manipulating DOM and rather do all changes on the model itself. Here is an example where I used two separate properties $scope.icon and $scope.locked to control icon style and button state: http://jsfiddle.net/CpZ9T/1/
In you case, I think you definitely should create a directive to encapsulate the button with its behavior. Here's an example:
HTML
<div ng-app='app'>
<form id="id_request" ng-controller="RequestCtrl">
<input id="id_title" name="title" ng-model="request.title" type="text" class="ng-valid ng-dirty" />
<my-button state="state" click-fn="submitRequest()"></my-button>
</form>
</div>
Javascript
angular.module('app', [])
.directive('myButton', function() {
return {
restrict: 'E',
scope: { state: '=', clickFn: '&' },
template: '<button type="submit" class="btn btn-primary" ng-click="clickFn()" ng-disabled="disabled">' +
' <i ng-class="cssClass"></i>' +
' {{ text }}' +
'</button>',
controller: function($scope) {
$scope.$watch('state', function(newValue) {
$scope.disabled = newValue !== 1;
switch (newValue) {
case 1:
$scope.text = 'Submit';
$scope.cssClass = '';
break;
case 2:
$scope.text = 'Submitting';
$scope.cssClass = 'icon-refresh icon-spin';
break;
case 3:
$scope.text = 'Error';
$scope.cssClass = 'icon-warning-sign';
break;
case 4:
$scope.text = 'Success';
$scope.cssClass = 'icon-ok';
break;
}
});
}
};
})
.controller('RequestCtrl', function ($scope, $http, $timeout) {
$scope.state = 1;
$scope.request = {};
$scope.submitRequest = function() {
$scope.state = 2;
$http({
method : 'GET',
url : '/ravishi/urSDM/3/',
data : $.param($scope.request),
headers : {
'Content-Type' : 'application/x-www-form-urlencoded',
}
}).
success(function(data, status, headers, config) {
$scope.state = 4;
$timeout(function() { $scope.state = 1; }, 1500);
console.log("success");
}).
error(function(data, status, headers, config) {
$scope.state = 3;
$timeout(function() { $scope.state = 1 }, 1500);
console.log("error");
});
}
});
jsFiddle here.

In Angular, how to redirect with $location.path as $http.post success callback

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;
}
});

Categories

Resources