second controller is not executing in Angular JS? - html

I'm new to AngularJS. I wrote code like this,
var myApp2 = angular.module('myApp2', []);
myApp2.controller('studentController', function($scope) {
$scope.student = {
firstName: "first name",
lastName: "last name",
fullName: function() {
var studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
var myApp1 = angular.module('myApp1', []);
myApp1.controller('productController', function($scope) {
$scope.quantity = 0;
$scope.cost = 0;
$scope.getTotalCost = function() {
return $scope.quantity * $scope.cost;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="col-lg-3" ng-app="myApp1" ng-controller="productController">
<label class="label label-default">Quantity :</label>
<input type="number" class="form-control" ng-model="quantity" />
<br>
<br>
<label class="label label-default">Cost :</label>
<input type="number" class="form-control" ng-model="cost" />
<br>
<br>
<label class="label label-success">Product :</label><span class="form-control disabled" ng-bind="getTotalCost()"></span>
</div>
<div class="col-lg-3" ng-app="myApp2" ng-controller="studentController">
<label class="label label-default">First name:</label>
<input type="text" class="form-control" ng-model="student.firstName" />
<br>
<br>
<label class="label label-default">Last name:</label>
<input type="text" class="form-control" ng-model="student.lastName" />
<br>
<br>
<label class="label label-success">You are entering:</label> <span class="form-control disabled" ng-bind="student.fullName()"></span>
</div>
the second div is not initialized. I think the controller is not executing.
If I remove the first div then it does.
What's wrong with it?

You will require manual bootstrapping for this, find link below :
https://stackoverflow.com/a/18583329/1939542

Related

INPUT DATE VALUE ANGULAR

SERVICE.TS
addP(nome: string, cognome: string, anno_n: string): Observable<any> {
return this.http.post<Partecipanti>(this.partecipantiUrl, {
nome: nome,
cognome: cognome,
anno_n: anno_n
}, this.httpOptions).pipe(
tap((newPartecipante: Partecipanti) => this.log(`partecipante aggiunto w/ id=${newPartecipante.id}`)),
catchError(this.handleError<Partecipanti>('addP'))
);
}
COMPONENT.TS
add(nome: string, cognome: string, anno_n: string): void {
this.PartecipantiService.addP(nome, cognome, anno_n).subscribe(res => {
console.log(res);
this.loadUser();
})
}
<form class="row row-cols-lg-auto g-3 align-items-center float-center" (ngSubmit)="add(nome.value, cognome.value, anno_n.value)" (ngSubmit)="loadUser()" style="justify-content: center;">
<div class="col-12">
<label class="visually-hidden" for="inlineFormInputGroupUsername">Nome</label>
<div class="input-group">
<input type="text" class="form-control" id="inlineFormInputGroupUsername" required #nome placeholder="Nome">
</div>
</div>
<div class="col-12">
<label class="visually-hidden" for="inlineFormInputGroupUsername">Cognome</label>
<div class="input-group">
<input type="text" class="form-control" id="inlineFormInputGroupUsername" required #cognome placeholder="Cognome">
</div>
</div>
<div class="col-12">
<label class="visually-hidden" for="inlineFormInputGroupUsername">Data di nascita</label>
<div class="input-group">
<input type="text" class="form-control" id="inlineFormInputGroupUsername" required #anno_n useValueAsDate placeholder="Data di nascita (GG/MM/AAAA)">
</div>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary shadow-lg">Salva</button>
</div>
</form>
How can I take the date value in my function "add"?
In my function add I have 3 field (name, surname and date), when I call my function add on a button I use (ngSubmit)="add(name.value, surname.value, date...?). What I have to use? Value is for string, I can't find something for Date! This part is on component.html Can you explain me how it works? My input is type="date"
I would suggest you use ngForm. This is the easiest for handling this scenario.
See here the Documentation: https://angular.io/api/forms/NgForm
Here is a working example i did: https://stackblitz.com/edit/angular-ivy-pqgewm?devtoolsheight=33&file=src/app/app.component.html
In Essence you want your HTML look like this:
<form #form="ngForm" (ngSubmit)="userService.submitForm(form)">
<div>
<label for="firstName">First Name</label>
<input name="firstName" id="firstName" type="text" ngModel required />
</div>
<div>
<label for="lastName">Last Name</label>
<input name="lastName" id="lastName" ngModel type="text" required />
</div>
<div>
<label for="dateOfBirth">Date of Birth</label>
<input name="dateOfBirth" id="dateOfBirth" ngModel type="date" required />
</div>
<br />
<button type="submit">Submit</button>
</form>
And your Submit function to look like this:
submitForm(form: NgForm) {
if (form.valid) {
const user: User = {
name: form.value['firstName'],
surname: form.value['lastName'],
birth: new Date(form.value['dateOfBirth']),
};
}
}

Required attribute doesn't work

required attribute doesn't work on my form. What am I doing wrong?
Here is my code in HTML:
<form id="main-contact-form" method="POST">
<fieldset class="form-group">
<input id="name" placeholder="Nome" class="form-control" type="text" tabindex="1" required /></fieldset>
<fieldset class="form-group">
<input id="email" placeholder="E-mail" class="form-control" type="email" tabindex="2" required /></fieldset>
<fieldset class="form-group">
<input id="phone" placeholder="Numero di telefono" class="form-control" type="tel" tabindex="3" required /></fieldset>
<fieldset class="form-group">
<textarea id="message" class="form-control" rows="8" placeholder="Scrivi un messaggio.." tabindex="5" required /></textarea></fieldset>
<fieldset>
<button name="submit" class="btn btn-primary" id="submitBtn">Invia Messaggio</button>
</fieldset>
</form>
<div id="feedback"></div>
Here is the php code in the head tag:
<script>
$(document).ready(function(){
$( "#submitBtn" ).click(function( event ) {
//values
var name=document.getElementById('name').value;
var email=document.getElementById('email').value;
var phone=document.getElementById('phone').value;
var message=document.getElementById('message').value;
var dataString = {"name": name, "email":email, "phone": phone, "message":message}
$.ajax({
type:"post",
url:"submitForm.php",
data: dataString,
success: function(html) {
$('#feedback').html(html);
}
});
event.preventDefault();
});
});
</script>

I want to save data generated by HTML form to JSON file

I want to save data generated from a an HTML form to JSON file in my computer, I'm totally new in the field. I have attached below the HTML and JavaScript code.
<form id="test" action="#" method="post">
<div class="form-group">
<label for="name">Name</label>
<input class="form-control" type="text" name="name" id="name" />
</div>
<div class="form-group">
<label for="check">Check if you like JavaScript</label>
<input type="checkbox" name="check" value="yes" />
</div>
<div class="form-group">
<label for="select">Select your favorite JavaScript framework</label>
<select name="select" class="form-control">
<option value="none" selected="selected">None</option>
<option value="jquery">jQuery</option>
<option value="angularjs">Angular</option>
<option value="mine">Mine, of course!</option>
</select>
</div>
<div class="form-group">
<label for="message">Leave a message</label>
<textarea class="form-control" name="message" rows="15" cols="30"></textarea>
</div>
<div class="form-group">
<label for="email">Email</label>
<input class="form-control" type="text" name="email" id="email" />
</div>
<div class="form-group">
<label for="password">Password</label>
<input class="form-control" type="password" name="password" id="password" />
</div>
<p>
<input type="submit" value="Send" class="btn btn-primary btn-block" />
</p>
</form>
<pre id="output"></pre>
(function() {
function toJSONString( form ) {
var obj = {};
var elements = form.querySelectorAll( "input, select, textarea" );
for( var i = 0; i < elements.length; ++i ) {
var element = elements[i];
var name = element.name;
var value = element.value;
if( name ) {
obj[ name ] = value;
}
}
return JSON.stringify( obj );
}
document.addEventListener( "DOMContentLoaded", function() {
var form = document.getElementById( "test" );
var output = document.getElementById( "output" );
form.addEventListener( "submit", function( e ) {
e.preventDefault();
var json = toJSONString( this );
output.innerHTML = json;
}, false);
});
})();
Instead of displaying the JSON content I want to store it in a JSON file.

Get array of object in AngularJS

I am using directive to add HTML div dynamically on the click of button.
How can I bind the model to controller scope object?
How can populate the scope object with enter data in dynamically added div?
How can I get list of object while click on save button.
Please find the code that I tried to add html div dynamically, but doesn't have any idea how to bind the entered data to scope object.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script type="text/javascript">
function FlatMember() {
this.firstName = '';
this.lastName = '';
this.emailId = '';
this.panNo = '';
this.phoneNo = '';
this.profileImage = ''
}
angular.module('myApp', []);
angular.module('myApp').controller('FlatMemberController', function ($scope) {
$scope.flatMembers = [];
$scope.addFlatMember = function() {
$scope.flatMembers.push(new FlatMember());
};
$scope.SaveFlatMember = function(){
console.log($scope.flatMembers);
}
});
angular.module('myApp').directive('memberInformation', function(){
return {
restrict: 'A',
template: '<div style="margin-top: 50px;">\
<div>\
<p>\
<label>First Name </label>\
<input type="text" id="firstName" /> \
<label>Last Name </label> <input type="text" id="lastName" />\
</p>\
<p>\
<label>Email </label> <input type="email" id="emailId"/>\
</p>\
<p>\
<label>PAN Number </label> <input type="text" id="panNo" data-ng-minlength="10"/>\
</p>\
<p>\
<label>Mobile </label> <input type="text" data-ng-minlength="10" id="phoneNo" />\
</p>\
</div> </div>',
replace: true,
transclude: false,
scope: {
memberInfo: '=memberInformation'
}
};
});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="FlatMemberController">
<button ng-click="addFlatMember()">Add new Member</button>
<div ng-repeat="flatMember in flatMembers"member-information="flatMember"></div>
<button ng-click="SaveFlatMember()">Save Member</button>
</div>
</body>
</html>
Your template is missing the ng-model bindings:
angular.module('myApp').directive('memberInformation', function(){
return {
restrict: 'A',
template: '<div style="margin-top: 50px;">\
<div>\
<p>\
<label>First Name </label>\
<input type="text" id="firstName" name="firstName" ng-model="memberInfo.firstName" /> \
<label>Last Name </label> <input type="text" id="lastName" name="lastName" ng-model="memberInfo.lastName" />\
</p>\
<p>\
<label>Email </label> <input type="email" id="emailId" name="emailId" ng-model="memberInfo.emailId" />\
</p>\
<p>\
<label>PAN Number </label> <input type="text" id="panNo" data-ng-minlength="10" name="panNo" ng-model="memberInfo.panNo" />\
</p>\
<p>\
<label>Mobile </label> <input type="text" data-ng-minlength="10" id="phoneNo" name="phoneNo" ng-model="memberInfo.phoneNo" />\
</p>\
</div> </div>',
replace: true,
transclude: false,
scope: {
memberInfo: '=memberInformation'
}
};
});

Validation of angular form without submit button

I am using anuglar.js form validation.
I want to check validation without form submit button.
This is my html.
<form name="userForm">
<input type="hidden" ng-model="StandardID" />
<div class="form-group">
<label for="email">Name:</label>
<input type="text" class="form-control" ng-model="Name" placeholder="Name" maxlength="50" required>
<span ng-show="userForm.Name.$dirty && !userForm.Name.$valid">Name is required.</span>
</div>
<div class="form-group">
<label for="pwd">Alias:</label>
<input type="text" class="form-control" ng-model="Alias" placeholder="Alias" maxlength="50" required>
</div>
<button type="submit" class="btn btn-info" ng-click="update()">Submit</button>
<button type="submit" class="btn btn-info" data-dismiss="modal">Cancel</button>
</form>
My controller js is.
$scope.update= function () {
alert($scope.userForm.Name.$valid);
if ($scope.userForm.Name.$valid) {
alert("Entry added");
}
}
It shows small dialog that says this field is required. I don't want this popup . Why span section does not show?
To do it, the key is use the name attribute in your <form> and in all of your inputs.
Following this way, angularjs will create a form instance where you can access all fields like myForm.myInput.$invalid
For example:
<form name="myForm" novalidate>
<label>My Input:</label>
<input type="text" name="myInput" ng-model="myInput" required>
<span ng-show="myForm.myInput.$dirty && myForm.myInput.$invalid">My Input is invalid.</span>
</form>
Check angular docs
HTML
<div ng-app="myApp">
<form name="cutome_form" ng-submit="submitForm()" novalidate>
<input type="text" name="name" class="form-control" ng-model="Name" placeholder="Name" maxlength="50" required>
<div ng-show="cutome_form.name.$dirty && cutome_form.name.$invalid">
<span class="error" ng-show="cutome_form.name.$error.required">The field is required.</span>
</div>
<div class="form-group">
<label for="pwd">Alias:</label>
<input type="text" name="alias" class="form-control" ng-model="Alias" placeholder="Alias" maxlength="50" required>
</div>
<div ng-show="cutome_form.alias.$dirty && cutome_form.alias.$invalid">
<span class="error" ng-show="cutome_form.alias.$error.required">The field is required.</span>
</div>
<button type="submit" ng-disabled="cutome_form.$invalid">Submit All</button>
</form>
</div>
directive
.directive('ngModel', function() {
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
elem.on('blur', function() {
ngModel.$dirty = true;
scope.$apply();
});
ngModel.$viewChangeListeners.push(function() {
ngModel.$dirty = false;
});
scope.$on('$destroy', function() {
elem.off('blur');
});
}
}
});