Values in $scope are not visible after location.path - javascript

I am facing problem while building a single page app with angularjs. My app has a login page. If authentication is success, app is routed to home page in which some data is displayed from $scope. However, no data is being displayed after login.
I am using location.path to route to home when sign in successful. For reference, I am trying to print "$scope.homePageDetails" in home.html but nothing is getting printed. Can someone say, what wrong am I doing and how can I resolve this issue?
index.html file:
<html>
<body>
<nav>
<ul>
<li ng-hide="isUserLoggedIn"> <span class="glyphicon glyphicon-log-in"></span> Login</li>
</ul>
</nav>
<div ng-view></div>
</body>
</html>
login.html file:
<div>
<form class="form-signin">
<input type="text" class="form-control" placeholder="Email" ng-model="userDetails.userName" required autofocus>
<input type="password" class="form-control" placeholder="Password" ng-model="userDetails.Password" required>
<button class="btn btn-lg btn-primary btn-block" type="submit" ng-click="signIn()">
Sign in</button>
</form>
home.html:
<p> {{homePageDetails}}</p>
angular module and controller:
app.controller('myCtrl', ['$scope','$http', '$location' function($scope,$uibModal,$http, $location, $window) {
$scope.signIn = function(){
$http({
url: "http://localhost:3050/postSignIn",
method: "POST",
headers: {'Content-Type': 'application/json; charset=utf-8'
},
data: $scope.userDetails
})
.then(function(response){
console.log('resp is',response);
$scope.isUserLoggedIn = true;
$location.path('/home');
$http({
url: "http://localhost:3050/getHomePageDetails",
method: "GET",
headers: {'Content-Type': 'application/json; charset=utf-8'
}
})
.then(function(response){
$scope.homePageDetails = response.data.slice(0);
}, function(response){
// failure callback
console.log('failure in getting homePageDetails',response);
});
},
function(response){
// failure callback
console.log('failure is',response);
});
}
}]);
module:
var app = angular.module('myApp', ['ngRoute']);
router:
app.config(function ($routeProvider, $locationProvider, $httpProvider) {
$routeProvider.when('/home',
{
templateUrl: 'home.html',
controller: 'myCtrl'
});
}

You can try this
$routeProvider
.when('/home',
{
templateUrl: 'home.html',
controller: 'myCtrl'
})
.when('/login',
{
templateUrl:'login.html',
controller:'myCtrl'
})

Related

AngularJS factory and controller code, not producing anything

When the below code is run nothing shows in my console to indicate anything went wrong, but as you can see in listService it's alerting withing the results, but the alert shows as "undefined".
I'm ultimately trying to get it to run a repeat to list all the Organizations on the view. Any help is appreciated!!
Here is my factory.
app.factory("listService", ["$rootScope", "$http", "$location", "$routeParams",
function($rootScope, $http, $location, $routeParams) {
var siteURL = "jdfyhgyjdfghyjdgfyhkjyhjk";
var svc = {};
var data = null;
svc.getListItems = function(listName) {
$http({
url: siteURL + "/_api/web/lists/GetByTitle('" + listName + "')/items",
method: "GET",
async: false,
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
},
success: function(response, status, headers, config) {
data = response.data.d.results;
alert(data);
},
error: function(response, status, headers, config) {
$rootScope.error = status;
}
});
}
return svc;
}
]);
Here is my controller.
app.controller("readOrganizationsCtrl", ["$scope", "$http", "$location", "$routeParams", "listService",
function($scope, $http, $location, $routeParams, listService) {
$scope.organizations = listService.getListItems('Organizations');
}
]);
And lastly here is my view.
<div class="form-group">
<input type="text" class="form-control" id="search" placeholder="Search organizations" data-ng-model="search" />
</div>
<table class="table table-stripped table-hover">
<thead>
<tr>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="organization in organizations | filter:search" data-ng-click="editOrganization($index)">
<td>{{organization.Title}}</td>
</tr>
</tbody>
</table>
<div class="form-group">
<button data-ng-click="addOrganization()" class="btn btn-primary">Add Organization</button>
</div>
{{"Error:" + error}}
after calling $http in controller you can easily get all your organizations from siteURL, here is working code:
JS:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $http) {
$http({
method: 'GET',
url: 'organizations.json',
headers: {
withCredentials: true,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
},
})
.then(function successCallback(data) {
$scope.organizations = data.data;
console.log($scope.organizations)
}, function errorCallback(response) {
console.log(response);
console.log('error');
});
});
HTML:
<tbody>
<tr data-ng-repeat="organization in organizations | filter:search" data-ng-click="editOrganization($index)">
<td>{{organization.name}}</td>
</tr>
</tbody>
plunker: http://plnkr.co/edit/aP7fLU1tfWwmZdCAYzIf?p=preview
Or, if you want to do it by factory, you can do it this way:
app.controller('MainCtrl', function($scope, $http, factory) {
factory.getOrganizations()
.then(function(data){
$scope.organizations = data.data;
console.log($scope.organizations)
})
.catch(function(){
})
});
app.factory('factory',function($http){
return {
getOrganizations: function(){
return $http.get('organizations.json');
}
};
})
plunker: http://plnkr.co/edit/UJUrTIGHGtjjccGAnHlk?p=preview

How to send empty string in routeparams in angular Js?

Hi I have a form in which I am sending a searched term and category id . It works fine as I am sending both things but if a user does not enter any thing only 'category id' goes, and in back end if searched term is empty all results are display to user.
But if I send an empty string in route params I redirect to myindex page. This is my app.js code.
when('/subcategory/:subcatId/:search', {
templateUrl: 'partials/subcategory.html',
controller: 'SubCategoriesController'
}).
My form
<form name="searchCategoryForm">
<div class="col-md-9 col-xs-10 col-sm-10">
<input class="form-control" placeholder="Find your item here...." ng-model="search" type="text" style="color:#09669c;">
</div>
<div class="col-md-2 col-xs-2 col-sm-2">
<a class="btn btn-primary" role="button" href='#/subcategory/{{cats[clicked_category].id}}/{{search}}'> Search</a>
</div>
</form>
My controller.js
$scope.search_term = $routeParams.search;
$scope.category_id = $routeParams.subcatId;
/* Search category form */
$scope.search_category = function () {
$http({
method: 'GET',
url: 'abc',
params: {"name": $scope.search_term, "category_id": $scope.category_id},
headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': $rootScope.keyword_auth_token}
})
.success(function (data) {
$scope.search_category_result = data.items;
console.log($scope.search_category_result);
})
.error(function (data) {
console.log(data);
});
};
/* Search category form ends here*/
if ($scope.search_term && $scope.category_id)
{
$scope.search_category();
}
I believe you should mark your search terms as optional by suffixing it with a question mark (?):
when('/subcategory/:subcatId/:search?', {
templateUrl: 'partials/subcategory.html',
controller: 'SubCategoriesController'
}).
See this answer for more info: Can angularjs routes have optional parameter values?

ng-model as initial input on form

I have an edit form that pushes data to a mongo db using express and angular. I am using ng-model for my data. The PUT works correctly to update the database. But I can't seem to make that found data as initial values on the input fields in my GET. I think I am binding things incorrectly. If that is the case, what am I doing wrong?
Thanks in advance.
My controller
app.controller('EditController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
var self = this;
$http({
method: 'GET',
url: '/users/' + $routeParams.id,
data: $routeParams.id
}).then(function(response) {
// console.log(response.data);
self.id = $routeParams.id;
self.name = response.data.name;
self.age = response.data.age;
self.gender = response.data.gender;
self.img = response.data.img;
});
this.editForm = function() {
console.log('editForm');
console.log('Formdata: ', this.formdata);
$http({
method: 'PUT',
url: '/users/' + $routeParams.id,
data: this.formdata,
}).then(function(result) {
self.formdata = {}
});
} // end editForm
}]);
// end EditController
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){
$locationProvider.html5Mode({enabled:true});
$routeProvider.when('/', {
templateUrl: 'partials/match_partial.html'
}).when('/edit/:id', {
templateUrl: 'partials/edit_partial.html',
controller: 'EditController',
controllerAs: 'editctrl'
})
}]);
My HTML
<div>
<a ng-href="/">
<br>
<h3 class="back">Back to Match</h3>
</a>
<h1 class="editHeader">
Edit {{editctrl.name}}
</h1>
<form ng-submit="editctrl.editForm()">
<input type="text" ng-model="editctrl.formdata.id" placeholder="{{editctrl.id}}">
<input type="text" ng-model="editctrl.formdata.name" placeholder="{{editctrl.name}}">
<input type="text" ng-model="editctrl.formdata.age" placeholder="{{editctrl.age}}">
<input type="text" ng-model="editctrl.formdata.gender" placeholder="{{editctrl.gender}}">
<input type="text" ng-model="editctrl.formdata.img" placeholder="{{editctrl.img}}">
<input type="submit">
</form>
</div>
You can simply set the whole object to receive the response.data, this way:
$http({
method: 'GET',
url: '/users/' + $routeParams.id,
data: $routeParams.id
}).then(function(response) {
// console.log(response.data);
// Here
self.formdata = response.data;
});
And it will automatically fills all inputs with the object properties.

User Based Login Page in AngularJS

Iam creating an angular app, in which the data will be displayed based on the user details entered in login page.
In brief, I need help in acheiving the below:
When user enters username and Password, url will be built with these username and password and url will be called so that an unique id(a numeric digit) will be generated for each user. This unique id will be in a JSON format like {"Record":[{"Id":12}]}
Now if the unique id is returned from url, tab.html has to be displayed or if null is returned, an error message of wrong credentials has to be displayed.
For a successfully loggedin user, a table in tab.html will be displayed based on uniqueid which is generated from username and password.
Below is the code I have:
login.html:
<form ng-submit=submit()>
<input type="text" name="username" placeholder="Username" ng-model="person.firstName" required />
<span class="error" ng-show="mainForm.usernamename.$error.required">required</span>
<input type="password" name="pswd" placeholder="Password" ng-model="person.pswd" required />
<span class="error" ng-show="mainForm.pswd.$error.required">required</span>
<div class="submit">
<div>
<label>
<input name="remember" type="checkbox" data-ng-model="remember" data-ng-click="rememberMe()"> Remember Me
</label>
</div>
<input type="submit" value="LOGIN">
</div>
<div class="row">
<div class="col-sm-10"><p>Forgot Password?</p></div>
</div>
</form>
tab.html:
<div ng-controller="SampleController">
<table class="table table-striped table-bordered table-hover dataTables-example">
<thead>
<tr>
<th>Name</th>
<th>ID</th>
<th>Qualification</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in tableContent" >
<td>{{x.Name}} </td>
<td>{{x.DT}}</td>
<td>{{x.Qualification}}</td>
</tr>
</tbody>
</table>
</div>
app.js:
var wc = angular.module('wc', []);
wc.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/login');
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'views/login.html',
controller: 'LoginCtrl'
})
.state('tab', {
url: '/tab1',
templateUrl: 'views/tab.html'
});
});
wc.controller('LoginCtrl', function ($scope,$http, $location) {
$scope.submit = function () {
$http.get("URL-PartAame=" + $scope.person.firstName + "&Password=" + $scope.person.pswd)
.success(function (data) {
//how to get the id from above url and display data based on condition//
$scope.tableData = data;
console.log(data)
$location.path('/tab1');
})
.error(function (response, status, headers, config) { });
}
});
wc.controller('SampleController', function ($scope, $http, $modal) {
$http.get("UrlA-UserId="returnedId)
.success(function (response) {
$scope.tableContent = response.Table;
});
};
I understood that this can be solved by using service or factory, but here how can a service be called along with the submit()? If this is not the correct way, please suggest the other way of doing it. Thanks in advance!!
Using $state.go and $stateParams service.
wc.controller('LoginCtrl', function ($scope,$http, $location, $state) {
$scope.submit = function () {
$http.get("URL-PartAame=" + $scope.person.firstName + "&Password=" + $scope.person.pswd)
.success(function (data) {
//how to get the id from above url and display data based on condition//
$scope.tableData = data;
console.log(data)
$state.go('tab', {id: the_necesarry_id});
//$location.path('/tab1');
})
.error(function (response, status, headers, config) { });
}
});
wc.controller('SampleController', function ($scope, $http, $modal, $stateParams) {
var returnedId = $stateParams.id;
$http.get("UrlA-UserId="returnedId)
.success(function (response) {
$scope.tableContent = response.Table;
});
};
Notice that you need add the id property contained in the $stateParams service in your url state.
.state('tab', {
url: '/tab1/:id',
templateUrl: 'views/tab.html'
});

RouteParams in AngularJS

I am trying to pass a routeParam to a $http.post in my Angular controller, but I dont seem to be passing the value correctly. Here is what I have below. Am an not using the $routeParams correctly? When using $scope.event_id = $routeParams.eventId; the partial page renders correctly with Event: {{event_id}} or Event: 5 for example.
I need the $http.post to be php/getItem.php?itemID=5
The HTML passing the event_id:
{{event.event_name}}
The routeProvider:
var pvApp = angular.module('pvApp', ['ngRoute']);
// configure our routes
pvApp.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'pages/home.html',
controller : 'mainController'
})
.when('/:eventId', {
templateUrl : 'pages/event_detail.html',
controller : 'eventController'
});
});
The Controller:
pvApp.controller('eventController', function($scope, $http, $routeParams) {
// $scope.event_id = $routeParams.eventId;
$http.post("php/getItem.php?itemID="+$routeParams.eventId).success(function(data){
$scope.items = data;
});
});
The Partial Page:
<div class="container">
<div class="row">
<div class="col-lg-12">
<h2>Event: {{event_id}}</h2>
</div>
</div>
</div>
first check
console.log($routeParams.eventId);
is print the event_id on the console correctly.
Then
Note that your using a POST request but your url like GET request.
change the request like below and try,
$http({
url: 'php/getItem.php',
method: "POST",
data: { itemID : $routeParams.eventId },
}).succes...
OR
$http.post('php/getItem.php', { itemID:$routeParams.eventId }).success...
here you can get the data in Php as,
$data = json_decode(file_get_contents("php://input"));
$data->itemID // to access name
OR
$http({
url: 'php/getItem.php',
method: "POST",
data: { itemID : $routeParams.eventId },
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
}).succes...
In Php,
$name= $_POST['itemID'];
may be this post will helps you.

Categories

Resources