How to pass data one page to another page using angular js? - javascript

Here I am Trying to Login with user credientials
if user is valid , I want to pass UserName,LastloginTime,Role values to another page using angular js
<form role="form" ng-app="MyApp" ng-controller="MasterController">
<div class="form-group">
<label>
Username</label>
<input type="text" class="form-control" placeholder="Username" required ng-model="username" />
</div>
<div class="form-group">
<label>
Password</label>
<input type="password" class="form-control" placeholder="Password" required ng-model="password" />
</div>
<div class="checkbox">
<label>
<input type="checkbox" ng-model="remember">
Remember my Password
</label>
</div>
<input type="button" value="Submit" ng-click="GetData()" class="btn btn-danger" />
<%--<button type="button" class="btn btn-danger" ng-click="GetData()">Submit</button>--%>
<span ng-bind="Message"></span>
</form>
js file here
$scope.GetData = function () {
debugger;
var data = { UserName: $scope.username, Password: $scope.password };
$http.post("api/Test/CheckUsername", data)
.success(function (data, status, headers, config) {
if (data != "") {
$scope.Employees = data;
window.location.href = "EmployeeMaster";
//$scope.Reporting = data;
}
else {
alert("Invalid Credientials");
}
});
}
I want to display values in a master page
<table class="table">
<tr ng-repeat="Emp in Employees">
<th>User </th>
<td>:</td>
<td>{{Emp.username}}</td>
</tr>
<tr>
<th>Designation </th>
<td>:</td>
<td>{{Emp.RoleName}}</td>
</tr>
<tr>
<th>Last Login </th>
<td>:</td>
<td>{{Emp.LastLogin}}</td>
</tr>
</table>
How can i pass the values login page to Home page?

I suggest creating a service to store your global data:
myApp.factory('DataService', function() {
var user = {
name: '',
role: ''
// and so on
};
return {
user: user
};
});
Just inject this to all your controllers and set and retrieve the data you need:
myApp.controller('MyCtrl', function($scope, DataService) {
// make your DataService available in your scope
$scope.DataService = DataService;
});
This lets you bind models globally to the DataService.

Check out angular-storage A Storage done right for AngularJS. It is great for storing user info/tokens/ any object.
Key Features
Uses localStorage or sessionStorage by default but if it's not available, it uses ngCookies.
Lets you save JS Objects
If you save a Number, you get a Number, not a String
Uses a caching system so that if you already have a value, it won't get it from the store again.
https://github.com/auth0/angular-storage

There is lot of ways of to achieve this
1) Use $rootscope like you use $scope like
$rootscope.userName = ""
Inject the $rootscope dependency in the controller where you want to show it and create an object name Employee and fill it with $rootscope.
2) use constant like
module.constant("userData", data);
Inject the userData dependency in the controller where you want to show it and create an object name Employee and fill it with userData.
3) You can use service/factory and save the data in localstorage/sessionstorage

to transfer data between pages, you can use stateParams:
in the routes file:
$stateProvider
.state('employeeMasterState', {
url: '/employeeMasterUrl/:employeeData',
templateUrl: 'info/employeeMaster.tpl.html',
controller: 'employeeMasterCtrl',
controllerAs: 'employeeMasterCtrlAs'
});
js:
$scope.GetData = function () {
debugger;
var data = { UserName: $scope.username, Password: $scope.password };
$http.post("api/Test/CheckUsername", data)
.success(function (data, status, headers, config) {
if (data != "") {
this.state.go('employeeMasterState',{employeeData:data});
}
else {
alert("Invalid Credientials");
}
});
}
in the next page js:
constructor($scope, $statePArams){
$scope.empData = $stateParams.data;
}

You can create a service or a factory to share data between webpages. Here is the documentation

Related

AngularJS: Get template attribute value in controller

I am a newbie of angularjs using version 1.6.4. I am using this module leon/angular-upload for upload functionality, minify version. On successful upload request, server return json object of uploaded file information on onSuccess(response) function as you can see in my user-registration.template.html file. Now i need to take this json object to my controller so that i can save this information in my database. Below is the few lines of my code.
user-registration.template.html:
<form role="form">
<div class="form-group float-label-control">
<label>Name</label>
<input type="text" placeholder="Name" class="form-control" ng-model="model.user.name">
</div>
<!-- leon/angular-upload -->
<div upload-button
url="/user_uploads"
on-success="onSuccess(response)"
on-error="onError(response)">Upload</div>
<div class="text-center">
<button type="button" class="btn btn-default" ng-click="model.save(model.user)">Save</button>
</div>
</form>
My component "user-registration.component.js":
(function(){
"use strict";
var module = angular.module(__appName);
function saveUser(user, $http){
var url = user.id > 0 ? __apiRoot + "/users/" + user.id : __apiRoot + "/users";
var dataObj = {
payload: JSON.stringify(user),
_method: "PUT"
}
return $http.post(url, dataObj);
}
function controller($http){
var model = this;
model.user = null;
model.save = function(user){
console.log(JSON.stringify(user));
saveUser(user, $http).then(function(response){
alert(response.data.msg);
});
}
}
module.component("userRegistration", {
templateUrl: "components/user-registration/user-registration.template.html",
bindings: {
value: "<"
},
controllerAs: "model",
controller: ["$http", controller]
});
}());
Try to put your server response data to rootScope model for Exempel :
$rootScope.serveResponse = response ;
and with this rootScope you can share your variable data between controller

Calling Httpget() in Multiviews/Nested states of UIRouter in AngularJS

Iam new to AngularJS and now facing an issue with uirouter multiple views. Searched for various examples,but couldn’t find a solution. Hope you will help.
I have a submit function inside controller in nested view. When a user clicks on submit, the subt_click() has to be invoked and an url has to be created based on the date provided and should call data from that url and display in a table.
<div ng-controller="MyController as ctrl">
<form class="form-horizontal">
<div class="form-group">
<div class="col-sm-5">
<p class="input-group">
<input type="text" class="form-control" datetime-picker="yyyy-MM-dd HH:mm" ng-model="dates.date3" is-open="ctrl.open.date3" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="ctrl.openCalendar($event, 'date3')"><i class="fa fa-calendar"></i></button>
</span>
</p>
</div>
</div>
</form>
<a ui-sref=".submit" class="btn btn-info" ng-click="subt_click()">Submit</a>
</div>
Below is how I have declared states and called the subt_click().
app.js:
var wc = angular.module('wc', ['ui.router','ui.bootstrap', 'ui.bootstrap.datetimepicker']);
wc.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/posts');
$stateProvider
.state('tab', {
url: '/tab1',
templateUrl: 'tab.html'
})
.state('tab.submit', {
url: '/submit',
templateUrl: 'tab-submit.html',
//controller: 'MyController'
})
.state('tabs', {
url: '/tabs',
templateUrl: 'tabs.html',
});
});
wc.controller('MyController', function ($scope, $http, $location, $filter) {
var that = this;
var in10Days = new Date();
in10Days.setDate(in10Days.getDate() + 10);
$scope.dates = {
date3: " ",
date4: " "
};
this.dates = {
date3: new Date(),
date4: new Date(),
};
this.open = {
date3: false,
date4: false,
};
// Disable weekend selection
this.disabled = function (date, mode) {
return (mode === 'day' && (new Date().toDateString() == date.toDateString()));
};
this.dateOptions = {
showWeeks: false,
startingDay: 1
};
this.timeOptions = {
readonlyInput: false,
showMeridian: false
};
this.dateModeOptions = {
minMode: 'year',
maxMode: 'year'
};
this.openCalendar = function (e, date) {
that.open[date] = true;
};
$scope.format = 'yyyy-MM-dd%20HH:mm';
debugger;
$scope.subt_click = function () {
var date = $filter("date")($scope.dates.date3, $scope.format);
$http.get("URLpartA"+date+"URLpartB")
.success( function(response) {
debugger
$scope.condition = response.Table
console.log(response)
});
};
});
tab-submit.html:
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in condition">
<td>{{x.ID}}</td>
<td>{{x.Name}}</td>
</tr>
</tbody>
</table>
Here is a plunk to check the code: plunker:http://plnkr.co/edit/3Iyao5aOt2tY7Ze104dp?p=preview.
the displayed table is empty and not the data from url(URL am using is from local host).There are no errors on console and from console.log(response) I could see the array objects from url.
Am not sure where this has went wrong. Will be really grateful if anyone can help!!
Check this plunker. I've added a controller, a dummy service to fetch data and used the service in resolve to inject data into the controller.

Angular not updating page after http request (scope issue?)

When my page loads, all the items in my mongo db are displayed. I have a form to input new entries, or delete entries. When creating or deleting, the http process works, but the new data is not updated in the DOM.
Most of the related questions I have researched suggest to make sure my ng-controller wraps the entire body, which it does. Other's suggest to use $apply, but I've also read that this is wrong. When I try it, I am alerted "in progress" anyway.
My only guess is that after the http request, a new scope is loaded and angular doesn't pick up on that. Or for some reason its just not reloading the data after my request. Here is my code, thanks for your help.
index.html
<body ng-controller="MainController">
<!-- list records and delete checkbox -->
<div id="record-list" class="row">
<div class="col-sm-4 col-sm-offset-4">
<!-- loop over records in $scope.records -->
<div class="checkbox" ng-repeat="record in records">
<label>
<input type="checkbox" ng-click="deleteRecord(record._id)">
{{ record.artist}} - {{ record.album }} - {{ record.bpm}}
</label>
</div>
</div>
</div>
<!-- record form data -->
<div id="record-form" class="row">
<div class="col-sm-8 col-sm-offset-2 text-center">
<form>
<div class="form-group">
<input type="artist" class="form-control input-lg text-center" placeholder="Artist" ng-model="formData.artist">
</div>
<div class="form-group">
<input type="album" class="form-control input-lg text-center" placeholder="Album" ng-model="formData.album">
</div>
<div class="form-group">
<input type="bpm" class="form-control input-lg text-center" placeholder="BPM" ng-model="formData.bpm">
</div>
<button type="submit" class="btn btn-primary btn-lg" ng-click="createRecord()">Add</button>
</form>
</div>
</div>
</div>
controller.js
angular.module('myApp', []).controller('MainController', ['$scope', '$http', function ($scope, $http) {
$scope.formData = {};
$scope.sortType = 'artist';
$scope.sortReverse = false;
//$scope.searchRecords = '';
$http.get('/api/records/')
.success(function(data) {
$scope.records = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
$scope.createRecord = function() {
$http.post('/api/records/', $scope.formData)
.success(function(data) {
//$scope.formData = {};
$scope.records = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
$scope.deleteRecord = function(id) {
$http.delete('/api/records/' + id)
.success(function(data) {
$scope.records = data;
console.log("delete record scope: " + data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
}])
Your controller JS looks fine - I would say from looking at this that you need to export the updated values from your mongoDB collection when the POST/DELETE is successful.
If you use Mongoose (mongoDB plugin), you can update your API code to send back the updated data upon success with something like this:
// POST
// --------------------------------------------------------
// Provides method for saving new record to the db, then send back list of all records
app.post('/api/records', (req, res) => {
// Creates a new record based on the Mongoose Schema
const newRecord= new Record(req.body);
// New record is saved to the db
newRecord.save((err) => {
// Test for errors
if(err) res.send(err);
// Now grab ALL data on records
const all = Records.find({});
all.exec((err, records) => {
// Test for errors
if(err) res.send(err);
// If no errors are found, it responds with JSON for all records
res.json(records);
});
});
});

Not able to insert value in DB via Angular JS with MVC4

I built a sample MVC application in which I tried to implement functionality to insert a record using angular js.
Here is the index cshtml page.
#{
ViewBag.Title = "Add User";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section adduser
{
#*Index.html*#
<div class="container-fluid" ng-app='MyData' ng-controller='DataController'>
<table class="table table-striped table-bordered table-responsive">
<tr>
<td>
<label class="text-primary">User Name:</label>
</td>
<td>
<input type="text" id="txtUserName" class="text-primary" required="required" ng-model="newUser" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" id="btnSubmit" class="btn btn-success" ng-click="AddUser()" />
</td>
</tr>
</table>
</div>
}
Here is the Model js code
var myData = angular.module('MyData', []);
Here is the controller JS code
myData.controller("DataController", function($scope) {
$scope.newUser = "";
$scope.addUser = function() {
$http.post("/Home/AddUser/", { newUser: $scope.newUser }).success(function (result) {
alert(result.success);
}).error(function(data) {
console.log(data);
});
};
});
Here is the post method inside controller which i am calling through angular js
[HttpPost]
public JsonResult AddUser(string name)
{
var db = new SchedulerEntities();
db.Users.Add(new User {Name = name});
db.SaveChanges();
return null;
}
I am adding an entry into DB from controller method but nothing is happening...
I think you need to declare $http in the function:
myData.controller("DataController", function($scope, $http) {
$scope.newUser = "";
$scope.addUser = function() {
$http.post("/Home/AddUser/", { newUser: $scope.newUser })
.success(function (result) {
alert(result.success);
}).error(function(data) {
console.log(data);
});
};
});

Getting undefined ngModel in Ionic AngularJS

I'm writing a HTML web app using Ionic. While trying to bind an input element to a $scope var, I'm getting undefined.
SignupCtrl.js:
angular.module('SUSU.controllers', [])
.controller('SignupCtrl',
function ($scope) {
/* Form entries */
$scope.signupForm = {
email: "",
emailConfirm: ""
};
});
signup.html:
<label class="item item-input">
<input type="email" placeholder="Email" ng-model="signupForm.email">
</label>
app.js:
angular.module('SUSU', ['ionic','SUSU.controllers'])
.config(function ($stateProvider, $urlRouterProvider) {
// Set and define states
$stateProvider
....
.state('tabs.signup', {
url: '/signup',
views: {
'login-tab': {
templateUrl: 'templates/signup.html',
controller: 'SignupCtrl'
}
}
});
While debugging I have noticed that the value of signupForm.email is undefined after inserting text to the email input. How can I bind those two and what am I doing wrong?
Guys I can't believe I have wasted so much time about that...
It's the type="email" who caused the problem. Because of some reason it doesn't work. When I changed it to type="text" it worked fluently.
Read more
There may be a better way to do this, but one way to achieve what you want is to do the following:
In your signup.html add a ng-change to your input:
<label class="item item-input">
<input type="email" placeholder="Email" ng-model="signupFormEmail" ng-change="updateEmail(signupFormEmail)">
</label>
Then in your controller add a method to $scope that will update your signupForm email property:
$scope.updateEmail = function(email){
$scope.signupForm.email = email;
}

Categories

Resources