Show data after POST with AngularJS - javascript

Im trying show the data that I have enterd, after an POST-action. But it does not work. How can I accomplish this?
Here is my HTML:
<div ng-controller="Test">
<div class="container">
<div class="col-sm-9 col-sm-offset-2">
<div class="page-header"><h1>Testar</h1></div>
<table class="table table-striped table-condensed">
<thead>
<tr>
<th>Namn</th>
<th>Efternamn</th>
<th>E-post</th>
</tr>
</thead>
<tr ng-repeat="info in test.data"><td>{{info.namn}}</td><td>{{info.efternamn}}</td><td>{{info.email}}</td></tr>
</table>
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate> <!-- novalidate prevents HTML5 validation since we will be validating ourselves -->
<div class="form-group" ng-class="{'has-error' : userForm.name.$invalid && !userForm.name.$pristine, 'has-success' : userForm.name.$valid }">
<label>Name</label>
<input type="text" name="name" class="form-control" ng-model="form.name" required>
<p ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block">Fel namn</p>
</div>
<div class="form-group" ng-class="{'has-error' : userForm.username.$invalid && !userForm.username.$pristine, 'has-success' : userForm.username.$valid && !userForm.username.$pristine}">
<label>Username</label>
<input type="text" name="username" class="form-control" ng-model="form.username" ng-minlength="3" ng-maxlength="8">
<p ng-show="userForm.username.$error.minlength" class="help-block">För kort</p>
<p ng-show="userForm.username.$error.maxlength" class="help-block">För långt</p>
</div>
<div class="form-group" ng-class="{'has-error' : userForm.email.$invalid && !userForm.email.$pristine, 'has-success' : userForm.email.$valid && !userForm.email.$pristine}">
<label>Email</label>
<input type="email" name="email" class="form-control" ng-model="form.email">
<p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">Ange korrekt e-post</p>
</div>
<button type="submit" class="btn btn-primary">Lägg till</button>
</form>
</div>
</div>
Here is my Controller:
as.controller('Test', function($scope, $http, $rootScope)
{
$http.get($rootScope.appUrl + '/nao/test/test')
.success(function(data, status, headers, config) {
$scope.test = data;
});
$scope.form = {};
$scope.submitForm = function(isValid) {
if(isValid)
{
$http.post($rootScope.appUrl + '/nao/test', $scope.form)
.success(function(data, status, headers, config) {
console.log(data);
$scope.test = data;
}).error(function(data, status) {
})
}
};
});
How can I view the data that I entered in the input fields, after the submit? As you can see, I've tried to set $scope.test = data, but that don't work.

You need to create a factory method for your $http post call which will return the data to the controller when you inject the factory.
angular.module('your factory module', [])
.factory('testFactory', function($http) {
return {
urMethod: function(callback) {
return $http({
<ur http call parameters>
}).
success(function(data) {
callback(data);
});
}
};
});
and in your controller:
as.controller('Test', ['testFactory', function($scope, $http, $rootScope,testFactory)
{
$http.get($rootScope.appUrl + '/nao/test/test')
.success(function(data, status, headers, config) {
$scope.test = data;
});
$scope.form = {};
$scope.submitForm = function(isValid) {
if(isValid)
{
testFactory.urMethod(function(data){
$scope.test = data;
});
}
};
}]);

please see here : http://jsbin.com/gagiwo/1/edit?js,output
as.controller('Test', function($scope, $http, $rootScope)
{
$http.get($rootScope.appUrl + '/nao/test/test')
.success(function(data, status, headers, config) {
$scope.test = data;
});
$scope.form = {};
$scope.submitForm = function(isValid) {
if(isValid)
{
$http.post($rootScope.appUrl + '/nao/test', $scope.form)
.success(function(data, status, headers, config) {
console.log(data); <-- data is object returned from server
$scope.datePosted = $scope.form; <-- $scope.form is your object posted to server
}).error(function(data, status) {
$scope.datePosted =$scope.form;
});
}
};
});

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

$http in Angular how to post from form data in to nodejs

I have this form and the data is not appear they do not pass to my back end :
<div ng-controller="searchController">
<form ng-submit="submit()">
<input type="text" name="name" ng-model="namegirl" />
<input type="text" name="namewod" ng-model="namewod" />
<input type="submit"/>
</form>
Now in my controller in script.js is this:
myApp.controller('searchController', ['$scope', '$filter', '$http', function ($scope, $filter, $http) {
let data = {
namegirl :$scope.namegirl,
name :$scope.namewod
};
console.log(data);
$http.post('/wodsearch',data)
.success(function (response) {
console.log(response.data);
})
.error(function (response, status) {
console.log(response);
});
}]);
Now i wand to pass my data from my form to the nodejs in my server i have this code:
app.post('/wodsearch',function(req, res ,next){
// how to get here the data from my angular
});
You call ng-submit="submit()" when you post the form but there is no submit() method in the searchControllers scope. Add it like this
myApp.controller('searchController', ['$scope', '$filter', '$http'
, function ($scope, $filter, $http) {
$scope.submit = function (){
let data = {
namegirl :$scope.namegirl,
name :$scope.namewod
};
console.log(data);
$http.post('/wodsearch',data)
.success(function (response) {
console.log(response.data);
})
.error(function (response, status) {
console.log(response);
});
};
}]);
Assuming you're using Express.
Then the data should be in req.body.

Issue with populating partial view with AngularJs and MVC

I am new to AngularJs. I am using a partial view for Create and Edit operation but facing some issue wile retrieving the data.
The data is being retrieved successfully from my MVC controller but is unable to populate the view.
Here is the JS I am using
(function (angular) {
'use strict';
angular.module('Sub_Ledger_Category_Create_app', [])
.controller('Sub_Ledger_Category_Create_ctrl', function ($scope, $http, $location) {
$scope.SubLedgerCategoryModel = {};
GetRequestType();
function GetRequestType() {
$http.get('/Common/Get_Action_Request')
.success(function (result) {
//debugger;
// $scope.SubLedgerCategoryModel = data;
if (result == "Create") {
$("#txt_Master_Subledger_Category").html("<h3 class='box-title'> Create Sub Ledger Category </h3>");
// $("#txt_Master_Accounting_Group_Group_id").val(0);
}
else {
$("#txt_Master_Subledger_Category").html("<h3 class='box-title'> Edit Sub Ledger Category</h3>");
//GetEditData();
$scope.GetEditData();
}
$("#Master_Subledger_Category").val(result)
NProgress.done();
})
.error(function (data, status, headers, config) {
NProgress.done();
$("div.failure").text("Unable to retrieve Request Type");
$("div.failure").fadeIn(300).delay(1500).fadeOut(400);
});
};
$scope.GetEditData = function () {
$http.get('/Master_Subledger_Category/GetEditData')
.success(function (data, status, headers, config) {
debugger;
$scope.SubLedgerCategoryModel = data;
console.log(data);
})
.error(function (data, status, headers, config) {
NProgress.done();
$("div.failure").text("Retrive Failure");
$("div.failure").fadeIn(300).delay(1500).fadeOut(400);
});
};
$scope.InsertSubledgerCategory = function () {
NProgress.start();
var Request_Type = $("#Master_Subledger_Category").val();
var Url_Master_Subledger;
if (Request_Type == "Create") {
Url_Master_Subledger = "/Master_Subledger_Category/Create_Master_Subledger_Category_Ajax";
}
else {
Url_Master_Subledger = "/Master_Subledger_Category/Test";
}
$http({
method: 'POST',
url: Url_Master_Subledger,
data: $scope.SubLedgerCategoryModel
}).success(function (data, status, headers, config) {
if (data.success === true) {
NProgress.done();
$("div.success").text("Successfully Created");
$("div.success").fadeIn(300).delay(1500).fadeOut(800);
$scope.SubLedgerCategoryModel = {};
console.log(data);
}
else {
NProgress.done();
$("div.failure").text("Saveing Failure");
$("div.failure").fadeIn(300).delay(1500).fadeOut(400);
}
}).error(function (data, status, headers, config) {
NProgress.done();
$("div.failure").text("Saveing Failure");
$("div.failure").fadeIn(300).delay(1500).fadeOut(400);
console.log($scope.message);
});
};
})
.config(function ($locationProvider, $sceProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
$sceProvider.enabled(false);
});
})(angular);
Here is the HTML:
<div class="form-horizontal" ng-app="Sub_Ledger_Category_Create_app">
<div class="box-body" ng-controller="Sub_Ledger_Category_Create_ctrl">
<div class="form-group">
<label for="txt_Master_Subledger_Category_Name" class="col-sm-2 control-label">Sub Ledger Category</label>
<div class="col-sm-10">
<input class="form-control" ng-model="SubLedgerCategoryModel.Sub_Ledger_Cat_Name" id="txt_Master_Subledger_Category_Name" name="txt_Master_Subledger_Category_Name" autofocus placeholder="Sub Ledger Category">
<input ng-model="SubLedgerCategoryModel.Sub_Ledger_Cat_ID" name="txt_Master_Subledger_Category_ID" id="txt_Master_Subledger_Category_ID" hidden />
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" value="Save" ng-click="InsertSubledgerCategory()" class="btn btn-info pull-right">Save</button>
<div class="text-red alert-box failure pull-right margin-r-5"></div>
<div class="text-green alert-box success pull-right margin-r-5"></div>
</div>
<!-- /.box-footer -->
</div>
</div>
Unfortunately I am unable to populate the view but in Console log I am able to view the data, helpful if anybody and help me.
AngularJs prevents loading HTML in this way by default. You might be getting an error on browser console: attempting to use an unsafe value in a safe context.
This is due to Angular's Strict Contextual Escaping (SCE) mode (enabled by default). Have a look to this for more information.
To resolve this issue you have 2 solutions:
$sce
$scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml(someHtmlVar);
ngSanitize: include the angular-sanitize.min.js resource and add the dependency in module.
hope this will help.
I have only changed the following
scope.SubLedgerCategoryModel = data;
to
scope.SubLedgerCategoryModel = data[0]:
and its resolved my issue.

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

Issue with angular animation and undefined javascript values

I am trying to get an angular animation to be triggered upon an unsuccessful login (either when the server sends a 4xx (e.g. 403) or when no credentials are provided).
Here is the controller:
.controller('SigninCtrl', ['$scope', '$rootScope', '$cookies', '$state', '$animate', 'signinService', function ($scope, $rootScope, $cookies, $state, $animate, signinService) {
$scope.signin = function () {
$scope.shake = false;
if ($scope.credentials) {
signinService.signin($scope.credentials, function (status, memberRole) {
$scope.shake = false;
//TODO: necessary to check status?
if (status === 200) {
...
}
},
function () {
$scope.shake = true;
});
}
else {
//TODO: only shakes/works once!
$scope.shake = true;
}
}
}]);
The form:
<form class="form-signin" ng-class="{shake: shake}" name="signinForm" ng-submit="signin()" novalidate>
<h2 class="form-signin-heading signin-title">{{'SIGNIN' | translate}}</h2>
<input type="email" ng-required name="username" ng-model="credentials.username" class="form-control" placeholder="{{'SIGNIN_FORM_EMAIL'| translate}}"/>
<input type="password" ng-required name="password" ng-model="credentials.password" class="form-control" placeholder="{{'SIGNIN_FORM_PASSWORD'| translate}}"/>
<button class="btn btn-lg btn-primary btn-block" type="submit">{{'SIGNIN' | translate}}</button>
<div class="forgot-password">
<a ui-sref="sendpasswordresetinformation">{{'SIGNIN_FORM_FORGOTTEN_PASSWORD' | translate}}</a>
</div>
</form>
However, if the form has no credentials in the inputs (nothing as in not even the empty string) the form shakes only once.
Can someone please help?
edit 1:
.factory('signinService', ['$http', function ($http) {
return {
signin: function (credentials, successCallback, errorCallback) {
var transform = function (data) {
return $.param(data);
}
return $http.post('/api/signin', credentials, {
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
transformRequest: transform
}).success(function (data, status, headers) {
if (status === 200) {
successCallback(status, headers('MEMBER_ROLE'));
}
else {
console.log('auth error');
successCallback('error');
}
}).error(function(data, status, headers) {
console.log("error!", data, status, headers);
errorCallback();
});
}
}
}]);
Changing the controller to :
...
$scope.signin = function () {
$scope.shake = false;
$scope.$apply();//ADDED!
...
fixed the issue. Thanks floribon...

Categories

Resources