Getting text from html scope - html

.controller('LoginCtrl', function($scope, $rootScope, $http, $state) {
window.localStorage.removeItem("loggedIn");
if(window.localStorage.getItem("loggedIn") == undefined) {
$scope.doLogin = function() {
var username = $scope.fName + " " + $scope.lName;
console.log(username);
//store login information
window.localStorage.setItem("username", username);
window.localStorage.setItem("password", $scope.password);
window.localStorage.setItem("loggedIn", true);
$http.post('http://localhost:8000/login',{
userName: window.localStorage.getItem("username"),
password: window.localStorage.getItem("password"),
token: $rootScope.devToken,
platform: ionic.Platform.platform()
});
alert("Login Success");
$state.go('main');
};
} else {
alert("Login Success");
$state.go('main');
}
})
<ion-content ng-controller="LoginCtrl">
<form ng-submit="doLogin()" style="display: block; margin: 100px">
<div class="list">
<label class="item item-input">
<input type="text" ng-model="fName" placeholder="First Name">
</label>
<label class="item item-input">
<input type="text" ng-model="lName" placeholder="Last Name">
</label>
<label class="item item-input">
<input type="password" ng-model="password" placeholder="Password" style="text-align: center">
</label>
<label class="item">
<button class="button button-block button-positive" type="submit">Register</button>
</label>
</div>
</form>
</ion-content>
I am trying to get the text from the html field fName and lName using $scope.fName because fName is a ng-model. How come it is returning undefined? I have the controllers set properly. I just can't figure out why username is outputting undefined? I am trying to load the app up at login.html and then once logged in, it will change the state to home.html. I could really use some help doing this.

The ion-content creates its own child scope. Try declaring a main scope object in your controller:
.controller('LoginCtrl', function($scope, $rootScope, $http, $state) {
$scope.data = {}
In your template:
<input type="text" ng-model="data.fName" placeholder="First Name">
In your login submit:
var username = $scope.data.fName + " " + $scope.data.lName;

You don't have validation in place to check whether the values are actually filled or not. The scope is not populated on initialization.
If you hit submit before adding anything there is no way those values can be populated and hence they are undefined.
Do something like this in submit button.
<button class="button button-block button-positive"
type="submit" ng-disabled="!fName||!lName">Register
</button>
Good Luck.
The code implementation is found here.
https://codepen.io/anon/pen/YGzxVz

http://ionicframework.com/docs/components/#toggle
i hope this works for you. A little change with CSS will do the trick

Related

Observe value changes when submit button pressed in Angular

I have an edit form as below which contains data in the input fields.
<ng-form #infoForm="ngForm" novalidate>
<div>
<label for="firstName">First Name :</label>
<input type="text"
class="form-control"
id="firstName"
name="firstName"
[(ngModel)]="in.firstName">
</div>
<div>
<label for="lastName">Last Name :</label>
<input type="text"
autocomplete="on"
class="form-control"
id="lastName"
name="lastName"
[(ngModel)]="in.lastName">
</div>
<button type="button" class="btn btn-primary" (click)="updateInfo(infoForm.value)">Update
</button>
</ng-form>
And I have the function in the component as below:
updateInfo(info: any) {
console.log(info);
}
This form return all the values (to the console) in the form when the Update button clicked, but I want to submit only the edited values instead of whole form. How could I implement it?
For this you can pass the form instead of its value to 'updateInfo' function and process it there. If user change the control value its state becomes 'dirty' from 'touched/pristine' and we can filter controls based on that.
Change in html:
<button type="button" class="btn btn-primary" (click)="updateInfo(infoForm)">Update
</button>
Change in *.ts file:
updateInfo(info: NgForm) {
const changedValues = Object.keys(info.controls)
.filter(key => info.controls[key].dirty === true)
.map(key => {
return { control: key, value: info.controls[key].value }
});
console.log(changedValues);
}

Default values are incorrect in html angular application

In this angularjs application I have a login page initially where the user types Username and Password. Once in the application, they can chose another page that requires a different username and password for database access. I want the database username to default to a different value than the login and the password to be blank with a placeholder of Enter a password. However, the defaults in the database page are using the initial login values.
This is the html of the login page:
<div class="form-group">
<label for="username" class="col-sm-2 control-label">Username</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="username" name="username" placeholder="Username" style="width: 80%" autofocus ng-model="credentials.username" />
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="password" name="password" placeholder="Password" style="width: 80%" ng-model="credentials.password" />
</div>
</div>
This is the html of the database login:
<div class="row" style="margin-top: 10px; margin-bottom: 10px;">
<label id="inputDBUserNameLabel" style="margin-left: 10px;" >User Name: </label>
<input id="inputDBUserNameText" type="text" ng-model="inputUserName" class="form-control demoInput" value="test" style="margin-left: 5px; width: 25%;"/>
</div>
<div class="row" style="margin-top: 10px; margin-bottom: 10px;">
<label id="inputDBPasswordLabel" style="margin-left: 10px;" >Password: </label>
<input id="inputDBPasswordText" type="password" ng-model="inputPassword" class="form-control demoInput" placeholder="Enter a password" style="margin-left: 5px; width: 25%;"/>
</div>
What am I doing wrong?
UPDATE
Below is the code to my controller when connecting to the the database.
When entering the correct username and password it works:
'use strict';
angular.module('vow-administration-ui')
.controller('UpgradeCtrl', ['$scope', 'UpgradeDB',
function($scope, upgradeDB) {
$scope.title = "Upgrade Database";
$scope.inputServerName = '';
$scope.inputDatabaseName = '';
$scope.inputUserName = '';
$scope.inputPassword = '';
$scope.outputServerName = '';
$scope.outputDatabaseName = '';
$scope.outputUserName = '';
$scope.outputPassword = '';
$scope.UpgradeDatabase = function(){
upgradeDB.save({
inputServerName: $scope.inputServerName,
inputDatabaseName: $scope.inputDatabaseName,
inputUserName: $scope.inputUserName,
inputPassword: $scope.inputPassword,
outputServerName: $scope.outputServerName,
outputDatabaseName: $scope.outputDatabaseName,
outputUserName: $scope.outputUserName,
outputPassword: $scope.outputPassword
}).$promise.then(function(response) {
var responseText = response;
console.log(responseText);
});
};
}]);
UPDATE
I removed the ng-model=inputUserName and both the UserName and Password fields were changed to the expected values. That is the UserName field had the default of test and the Password field had the placeholder of Enter a password even though I did NOT remove the ng-model attribute from the password field.
UPDATE
Login Controller:
angular.module('vow-administration-ui')
.controller('LoginCtrl', function($scope, $rootScope, $location, AUTH_EVENTS, AuthService) {
$scope.isProcessing = false;
$scope.credentials = {
domain: '',
username: '',
password: ''
};
$scope.login = function() {
AuthService.authenticateAdministrator($scope.credentials).then(function() {
$scope.errorMessage = '';
$scope.errorState = false;
$location.path('/launch').replace();
},
function(error) {
AuthService.destroyToken();
$scope.errorMessage = 'Failed to authorize. ' + error.data.ExceptionMessage;
$scope.errorState = true;
});
};
});
Corrected the problem...
It is Google Chrome that was the problem.
Apparently, when you use ids that are a form of 'username' and 'password' Chrome tries to 'help' by inserting the previous text that was used as a username and password.
To fix the problem, I changed my ng-model names to variations of UsrNm and Pwd.
It works now.

ngSubmit HTML attribute using angular template variable

I have two methods ngMake and ngUpdate. I have one form, PostForm. I want to reuse the same form, but add different functionality depending on the url.
I gain information about the url using
Controller
if ($location.path() === '/makepost') {
$scope.FormTitle = 'Make a Post';
$scope.FormAction = 'server/blog/makepost.php';
$scope.FormMethod = 'POST';
$scope.FormSubmit = "ngMake()"
};
if ($location.path().indexOf('update') !== -1) {
$scope.FormTitle = 'Update a Post';
$scope.FormAction = null;
$scope.FormMethod = 'POST';
$scope.FormSubmit = "ngUpdate()";
};
HTML Form
<div ng-controller="BlogController as blog">
<h3 class="text-center">{{FormTitle}}</h3>
<form ng-show='user != null' ng-submit="{{FormSubmit}}" role="form" class="form-group" name="PostForm">
<label>Title: </label>
<div ng-class="(PostForm.Title.$dirty && PostForm.Title.$invalid) ? 'has-warning' : 'has-success'" class="form-group has-feedback">
<input data-ng-model="post.Title" data-ng-minlength="3" data-ng-maxlength="255" name="Title" type="text" class="form-control" placeholder="Title" required/>
<span ng-class="(PostForm.Title.$dirty && PostForm.Title.$invalid) ? 'glyphicon-warning-sign' : 'glyphicon-ok'" class="glyphicon form-control-feedback"></span>
</div>
<label>Content: </label>
<div ng-class="(PostForm.Content.$dirty && PostForm.Content.$invalid) ? 'has-warning' : 'has-success'" class="form-group has-feedback">
<textarea data-ng-model="post.Content" rows="8" name="Content" type="text" class="form-control" placeholder="Content" required></textarea>
<span ng-class="(PostForm.Content.$dirty && PostForm.Content.$invalid) ? 'glyphicon-warning-sign' : 'glyphicon-ok'" class="glyphicon form-control-feedback"></span>
</div>
<div ng-controller="AuthController as auth">
<input class="ng-hide" type="number" data-ng-model="post.UserID" name="UserID" value="{{user.ID}}">
</div>
<br>
<input type="submit" ng-class="(PostForm.$valid) ? 'btn-success' : 'disabled'" class="btn btn-block btn-default">
</form>
<p ng-show='user == null' class="text-center">You must be logged in in order to {{FormTitle | lowercase}}</p>
Explination
The {{FormSubmit}} template variable probably executes afterwards and causes a problem which doesn't permit the form to execute. I am open to suggestions, I want to reuse the same form. I read that ngSubmit requires a type="submit" button or input element contained within the form tags, I have that. I do not have any ng-clicks which might hinder the form.
I am open to suggestions
If there are any other problems with the form or the entire project please let me know, even if it is just a "bette practice".
The full project
https://github.com/AquaSolid/RAMA_Angular_PHP
Basically, I wised up. I contained the logic in the back-end. I created a function to choose which function to use. Meanwhile the the form contains the attribute ng-submit="chooseSubmit()". That's about it..
$scope.chooseSubmit = function() {
if ($scope.FormSubmit) {
if ($scope.FormSubmit === 'ngMake()') {
$scope.ngMake();
} else {
$scope.ngUpdate();
};
}
};

how to validate particular input field using angularjs?

I am trying to validate some input fields using angularJS. I found some example. But they are validating entire form.
<div ng-app="myApp" ng-controller="myCtrl">
<form name="myform">
<input type="text" ng-model='name' ng-required="true" />
<input type="password" ng-model='password' ng-required="true" />
<button ng-click="myform.$valid && preview()">Preview</button>
<button ng-click="myform.$valid && update()">Update</button>
</form>
</div>
and controller code is
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name=undefined;
$scope.preview = function(){
alert("Previewed");
};
$scope.update = function(){
alert("Updated");
}
});
The above code validating the fields based on form name. But I wanted to know is there any way to validate that particular input field ?
DEMO
Yes you can, you must specify a name for the input like
<div ng-app="myApp" ng-controller="myCtrl">
<form name="myform">
<input type="text" name='name' ng-model='name' ng-required="true" />
<input type="password" ng-model='password' ng-required="true" />
<button ng-click="myform.$valid && preview()">Preview</button>
<button ng-click="myform.$valid && update()">Update</button>
</form>
</div>
then you can check if the name is valid with myForm.name.$valid
Check out the fiddle here.
Just add a name to the input filed and follow the same as you did to the form.
HTML:
<div ng-app="myApp" ng-controller="myCtrl">
<form name="myform">
<input type="text" ng-model='name' ng-required="true" name="txtName" />
<input type="password" ng-model='password' ng-required="true" />
<button ng-click="myform.$valid && preview()">Preview</button>
<button ng-click="myform.$valid && update()">Update</button>
<div>Status of name: <span style="color: blue">{{myform.txtName.$valid}}</span></div>
</form>
</div>
JS:
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.name = undefined;
$scope.preview = function () {
alert("Previewed");
};
$scope.update = function () {
alert("Updated");
}
});

Putting value to hidden input and then getting it in POST variable

I am trying to get an input value with AngularJS from input field to another hidden input field (in another form in the same page) so I can transmit it later if user presses submit on the other form.
<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
//down the code...
<form name="whatever" method="post">
<input type="hidden" ng-bind="name" value="">
</form>
</div>
When I inspect the code after I put data in the visible input field all looks fine - so when I change the data inside the visible input I can see it in the hidden input too but I can't see it in the POST variable after I submit the form - I guess it's because it doesn't change the value field in the hidden input just what between the and .
How can I get this to work so that I change the value of an hidden input - but not what between the opening and closing input field?
Just Replace ng-bind with ng-value like:
<input type="hidden" ng-value="name">
(Credit to Himmet Avsar)
I see you answered yourself already. Anyway you should go for more "angular way" when handling your forms, letting angular do the "posting". For example:
HTML template
<body ng-controller="MainCtrl">
<form name="form1"
ng-submit="submit()">
Name: <input type="text"
class="form-control"
name="name"
ng-model="user.name"
required>
<div class="alert alert-warning"
ng-show="form1.name.$error.required">
Required field
</div>
<input type="submit"
class="btn btn-primary"
value="submit">
</form>
<div class="alert"
ng-class="{ 'alert-success': response.status === 200, 'alert-danger': response.status !== 200 }"
ng-show="response !== null">
DATA: {{ response.data }}<br>
HTTP {{ response.status }} {{ response.statusText }}
</div>
<hr>
<form name="form2" ng-submit="submit()">
Name: <input type="text"
class="form-control"
ng-model="user.name">
Age: <input type="number"
class="form-control"
min="1"
max="100"
ng-model="user.age">
<input type="submit"
class="btn btn-primary"
value="submit" disabled>
</form>
</body>
JavaScript
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $http) {
$scope.user = {};
$scope.response = null;
$scope.submit = function() {
$scope.response = null;
$http({
method: 'POST',
url: 'http://jsonplaceholder.typifcode.com/posts',
data: $scope.user,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
$scope.response = response;
}).catch(function (response) {
$scope.response = response;
});
};
});
You'll get something like
Related plunker here http://plnkr.co/edit/M7zQzp