Changing CSS property if no input is provided (Angular JS) - html

I am making a quiz using angular js.The first page of the quiz requires you to enter your name and doesn't allow you to go further if no input is provided.I want to animate input field more like the shake animation on this site (http://daneden.github.io/animate.css/) if the input field is empty and the user presses the start button.Please help me out.
CODE html :
<p>What's your name?</p>
<input type = "text" class = "playername" ng-model = "playername">
<h2>Welcome {{playername}}!</h2>
<p>Click start if you're ready!</p>
<p class = "btn" ng-click = "startQuiz()">START</p>
CODE angular :
$scope.presentQues = -1;
$scope.startQuiz = function(){
if ($scope.playername != null){
$scope.presentQues = 0;
}
}
PS. this is not the full code.

Building on #Chris's answer, if you wrap it in a form, you can also use the form.$submitted variable to check if the form has been submitted.
ng-class uses the following format: ng-class={'css-class':truthy-condition-to-evaluate
Try the following code (this will have to be changed if you already are wrapping everything in a form):
<div ng-controller="myCtrl as ctrl">
<form name="myForm">
<p>What's your name?</p>
<input type = "text" name="playername" class = "playername" ng-class="{'animated shake': !ctrl.playername && myForm.$submitted}" ng-model = "ctrl.playername">
<h2>Welcome {{ctrl.playername}}!</h2>
<p>Click start if you're ready!</p>
<input type="submit" class = "btn" ng-click = "startQuiz()" value="START">
</form>
</div>
Now, if the player submits the form without typing anything, angular will apply the animated and shake css classes to the text input.
Look at my plunker to view it in action.

There are many ways of doing this, one I can see is using ng-class.
<!-- add class 'bounceInUp' if the scope var 'isEmpty' is true -->
<input type="text" class="playername" ng-class={'bounceInUp':isEmpty,} ng-model="playername">

Related

Hiding and Showing Edit Input not working(Angular)

I'm trying to make an Edit button, with an input field that appears/disappears when the button is pressed. It was working previously, however when I tried to make a Display form, it doesn't seem to recognize the "title.value" This is very strange. I'm using Boolean for an "edit" variable combined with a *ngIf to show/hide the form. If I take the *ngIf="edit" off, it works normally as a form that displays what you're written. Am I missing something?
Here's the HTML:
<input type="text" #title *ngIf="edit"/>
<button (click)="edit = !edit">Edit</button>
<button (click)="getTitle(title.value)">Get Title</button>
<h2>{{groupTitle}}</h2>
and here's the .ts:
public edit = false;
public groupTitle = "";
getTitle(val) {
this.groupTitle = val;
}
You have a problem with implementing together the ngIf directive and a reference to your input element as #title. In that case you can use hidden instead of ngIf.
Here's your html:
<input type="text" #title [hidden]="!edit"/>
<button (click)="edit = !edit">Edit</button>
<button (click)="getTitle(title.value)">Get Title</button>
<h2>{{groupTitle}}</h2>
There are couple more elegant ways to bind a value and render it on a page.
The first one is to get rid of the Get title button and use (input) method directly on an input element.
In that case, Html looks like:
<input type="text" #title *ngIf="edit" (input)="getTitle(title.value)"/>
<button (click)="edit = !edit">Edit</button>
<h2>{{groupTitle}}</h2>
The second one is to use [(ngModel]) instead of the getTitle method and bind your input value directly to the groupTitle variable.
Html will look like:
<input type="text" #title *ngIf="edit" [(ngModel)]="groupTitle"/>
<button (click)="edit = !edit">Edit</button>
<h2>{{groupTitle}}</h2>
Your .ts file:
edit = false;
groupTitle = "";

How to reset check status in html

I have popup in HTML
<div id="term_flags" class="term_flags">
<div class="modal-users-content flagsContent">
<div class="modal-users-header">
<span class="close" ng-click="closeFlagsPopup()">×</span>
<a> Check terminal flags </a>
</div>
<div class="modal-flags-body">
<div class="checkBoxes">
<div class="checkerDiv">
<input type="checkbox" ng-model='reservedFlag' ng-click='changeReservedStatus(reservedFlag)' value="flag" ng-checked="reservedFlag"> Reserved
</div>
<div class="checkerDiv">
<input type="checkbox" ng-model='seasonFlag' ng-click='changeSeasonStatus(seasonFlag)' value="flag" ng-checked="seasonFlag"> Season
</div>
<div class="checkerDiv">
<input type="checkbox" ng-model='networkFlag' ng-click='changeNetworkStatus(networkFlag)' value="flag" ng-checked="networkFlag"> Network
</div>
</div>
<div class="saveFlags">
<button class="button button6" name="changeFlags" value="Change Flags" type="submit" ng-click="saveFlags(item.terminalId)"> Save <p> </button>
</div>
</div>
<div class="modal-footer"></div>
</div>
</div>
this div's display is none in the beginning. but some ng-click is called from outside of this div and display is changed from none to block and initializes checkbox statuses in this angular function
$scope.changeFlagStatus = function(item)
{
$scope.reservedFlag=(item.reservedFlag=='T')?true:false;
$scope.networkFlag=(item.networkFlag=='T')?true:false;
$scope.seasonFlag=(item.seasonFlag=='T')?true:false;
document.getElementById('term_flags').style.display = "block";
}
everything is okay , but when i click on reservedFlag changeReservedStatus(reservedFlag) method was called and change reservedFlag's checked status
$scope.changeReservedStatus = function(item) {
$scope.reservedForSave=item;
}
I saved this status in other variable and close my popup windows document.getElementById('term_flags').style.display=none
when i open this popup window again my function changeFlagStatus(item) is called again and initializes my variables for checkbox correctly but my checkbox are incorrect checked .
In example when i opened my popup window first time my variables after initialize were
$scope.reservedFlag=true;
$scope.networkFlag=false;
$scope.seasonFlag=true;
and my checkbox statuses were
reservedFlag = checked
networkFlag = unchecked
seasonFlag = checked
then i clicked on reservedFlag and changed his status from checked to unchecked and close my popup windows.
then i opened it second time and changeFlagStatus(item) method is called again to initialize my variables again for checkbox statuses
and i want to get
reservedFlag = checked
networkFlag = unchecked
seasonFlag = checked
again, but result is
reservedFlag = unchecked
networkFlag = unchecked
seasonFlag = checked
How can i get it ?
Angularjs won't work pretty good with $scope's properties for primitive variables when used again and again.
I would recommend you to declare an object to scope and set these flags as properties to this object.
$scope.flags = {};
$scope.changeFlagStatus = function(item)
{
$scope.flags.reservedFlag=(item.reservedFlag=='T')?true:false;
$scope.flags.networkFlag=(item.networkFlag=='T')?true:false;
$scope.flags.seasonFlag=(item.seasonFlag=='T')?true:false;
document.getElementById('term_flags').style.display = "block";
}
and the html part as
<input type="checkbox" ng-model='flags.reservedFlag' ng-change='changeReservedStatus()' value="flag" ng-checked="flags.reservedFlag"> Reserved
Instead of ng-click, I would recommend to use ng-change because that is the event to be used with checkbox. If you use ng-change, the injection of the model as a parameter can be avoided which helps in utilizing angularjs's feature of 2-way binding.
You can add ng-true-value and ng-false-value to the checkbox with true and false to make it more easier to handle instead of ng-value.
I would write the html part like this.
<input type="checkbox" ng-model='flags.reservedFlag' ng-change='changeReservedStatus()' ng-true-value="true" ng-false-value="false"> Reserved
Hope this will fix the issue.

Angular 2 html form validation

I've created a form using html validations with Angular 2.
I want to to check the sate of the inputs (no empty, correct format, etc) when the user click to a certain button. At the moment I'm doing it as following:
<form id="memberForm" #memberForm="ngForm" >
<input
type="text"
id="MemberName"
required
name="MemberName"
[(ngModel)]="newMember.name">
</form>
<div
[ngClass]="{'button_disabledButton' : !memberForm?.valid}"
(click)="onSubmit(memberForm?.valid, memberForm);">
<span>Next</span>
</div>
With this, I'm only evaluating the input once clicked and focus out. How can I make it hapens when the user click in the "Next" element?
You should make getter/setter solution for your ngModel input.
In the .ts file in the appropriate class put this:
savedVar:string = '';
get variable(): string {
return this.savedVar;
}
set variable(str: string) {
this.savedVar = str;
// do your validation
}
In template use ngModel=variable like this:
<input [(ngModel)]="variable">

appear an html element by clicking on a button with angularjs

I have an html form ( ) , I want that it is displayed when I click on a button.
the declaration of the form is the following :
<div id = "formulaire" class="gl" >
and the button is :
Edit
I use angularjs in my code . Please help me.
It better to use a simple variable than a function in this case. I would also recommend using controller scope when setting variables instead of the application scope so you don't run into issues with the variables when your application becomes large.
I also picked data-ng-click over ng-click because it will allow the html to validate correctly (which can be checked using the W3's validator).
Try this...
"use strict";
angular.module('myApp', [])
.controller("myController", function() {
this.edit = false;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<div data-ng-app="myApp" data-ng-controller="myController as ctrl">
Edit
<div id="formulaire" class="gl" data-ng-show="ctrl.edit">
<form>
<fieldset>
<label>Field:</label>
<input type="text" />
</fieldset>
</form>
</div>
</div>
Have you looked into the ngShow directive? It ables you to show or hide a DOM element depending on whether the attribute expression resolves to a truthey or falsey value.
Add model change on click
Edit
And then display the form if model is true
<div id = "formulaire" class="gl" ng-if="show">

Angular, validate form when submitting from outside form [duplicate]

Given this code:
<div ng-controller="MyCtrl">
<form ng-submit="onSubmitted()">
Header inputs:
<input type="name" ng-model="sample" required/>
<input type="name" ng-model="sampleX" required/>
<input type="submit" value="This submit triggers validation. But I wanted to put this button at the end of the page"/>
</form>
<hr/>
Some other form here. Think line items
<hr />
<a class="btn" ng-click="/* what could should be put here, so this can trigger the firt form's validation, then submit? */">Wanted this submit button to trigger the validation+submit on the form in which this button doesn't belong</a>
</div>
var app = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.onSubmitted = function() {
alert('submitted!');
};
}
I want the last button to trigger the validation(then submit when things are valid) on first form. As of now, only the button inside the form can trigger that form's validation and submission. Is there any possible way for a button outside the form to do that?
Live test: http://jsfiddle.net/dzjV4/1/
You can create directive which you can then attach to <a class="btn".... Check this jsfiddle
http://jsfiddle.net/dzjV4/2/
Note that I added to <input type='submit' id='clickMe'... and linked it with link at the bottom <a class='btn' linked="clickMe"...
for (control of $scope.[form name].$$controls) {
control.$setDirty();
control.$validate();
}
You can try the above codes. Make it running before submit.
Ideally there'd be a programmatic way to cause validation to re-run across a form. I have not investigated that completely but had a situation that required multiple controls to be re-validated based on different data in the scope -- without the user interacting with the individual controls. This arose because the form had two action buttons which each required different validation rules be in play when they were clicked.
The UI requirement changed before I fully implemented forcing re-validation but before it did I got most of what I needed by copying and then re-setting the form's data. This forced re-validation across the form within the current scope. Basically, it's along the lines of the following (not tested, but taken from the code that was working). In this case the form's data was bound to the properties in one object.
var formData = $parse(<form's model>);
var dataCopy = angular.copy( formData($scope) );
formData.assign( $scope, dataCopy );
This may or may not be acceptable, but if you can get away with the SUBMIT button being disabled until the form is completed, you can do this:
<form name="formName">
<input ng-required="true" />
</form>
<button ng-click="someFunction()" ng-disabled="formName.$invalid" />
It's also worth noting that this works in IE9 (if you're worried about that).
Give your form a name:
<div ng-controller="MyCtrl">
<form name="myForm">
<input name="myInput" />
</form>
</div>
So you can access your form validation status on your scope.
app.controller('MyCtrl', function($scope) {
$scope.myForm.$valid // form valid or not
$scope.myForm.myInput // input valid or not
// do something with myForm, e.g. display a message manually
})
angular doc
There is no way to trigger browser form behavior outside of a form. You have to do this manually.
Since my form fields only show validation messages if a field is invalid, and has been touched by the user:
<!-- form field -->
<div class="form-group" ng-class="{ 'has-error': rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched && rfi.rfiForm.stepTwo.Parent_Suffix__c.$invalid }">
<!-- field label -->
<label class="control-label">Suffix</label>
<!-- end field label -->
<!-- field input -->
<select name="Parent_Suffix__c" class="form-control"
ng-options="item.value as item.label for item in rfi.contact.Parent_Suffixes"
ng-model="rfi.contact.Parent_Suffix__c" />
<!-- end field input -->
<!-- field help -->
<span class="help-block" ng-messages="rfi.rfiForm.stepTwo.Parent_Suffix__c.$error" ng-show="rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched">
<span ng-message="required">this field is required</span>
</span>
<!-- end field help -->
</div>
<!-- end form field -->
I was able to use this code triggered by a button to show my invalid fields:
// Show/trigger any validation errors for this step
angular.forEach(vm.rfiForm.stepTwo.$error, function(error) {
angular.forEach(error, function(field) {
field.$setTouched();
});
});
// Prevent user from going to next step if current step is invalid
if (!vm.rfiForm.stepTwo.$valid) {
isValid = false;
}