Is there a way to write these angular bindings more efficiently? - javascript

I have a form embedded in a view in my Angular JS 1.2.6 application.
<div class="container" ng-controller="LoginCtrl as signin">
<div class="row">
<div class="col-md-4">
<form name="signin.myForm" novalidate autocomplete="off">
<h1>Sign In</h1>
<div class="form-group" ng-class="{'has-error': (signin.myForm.name.$error.required || signin.myForm.name.$error.minlength) && signin.myForm.name.$dirty}">
<label>Name</label>
<input class="form-control" type="text" name="name" ng-model="signin.myForm.data.name" required ng-minlength="3">
<span class="help-block" ng-show="signin.myForm.name.$error.required && signin.myForm.name.$dirty" >Name is required.</span>
<span class="help-block" ng-show="signin.myForm.name.$error.minlength && signin.myForm.name.$dirty" >Must be at least 3 characters.</span>
</div>
<button class="btn btn-primary" ng-disabled="!signin.myForm.$valid" ng-click="signin.submit()">Sign in</button>
</form>
</div>
with the controller being:
app.controller('LoginCtrl', ['$log',function($log){
var ctrl = this;
ctrl.submit = function(){
console.log(ctrl.myForm);
if(ctrl.myForm.$valid){
console.log('the form is valid');
}
};
}]);
As you can see, to get the form field's data to be part of the same scope as the signin I was taught to first do ng-controller="LoginCtrl as signin" and then I wind up with convoluted names for models and properties like signin.myForm.name.$error.required
Is this the correct way to do it? It seems to work, but although I am a noob this seems like a bit tangled to me. Is this really the best practice?

I think it's more common to see something like this, where you attach things to an injected $scope instead of this, and then you don't have to put a namespace qualifier on the references in the HTML.
<div class="container" ng-controller="LoginCtrl">
<div class="row">
<div class="col-md-4">
<form name="myForm" novalidate autocomplete="off">
<h1>Sign In</h1>
<div class="form-group" ng-class="{'has-error': (myForm.name.$error.required || myForm.name.$error.minlength) && myForm.name.$dirty}">
<label>Name</label>
<input class="form-control" type="text" name="name" ng-model="signin.myForm.data.name" required ng-minlength="3">
<span class="help-block" ng-show="signin.myForm.name.$error.required && myForm.name.$dirty" >Name is required.</span>
<span class="help-block" ng-show="myForm.name.$error.minlength && myForm.name.$dirty" >Must be at least 3 characters.</span>
</div>
<button class="btn btn-primary" ng-disabled="!myForm.$valid" ng-click="submit()">Sign in</button>
</form>
</div>
app.controller('LoginCtrl', ['$scope', '$log',function($scope, $log){
$scope.submit = function(){
console.log($scope.myForm);
if($scope.myForm.$valid){
console.log('the form is valid');
}
};
}]);

Related

Parameter is not passed to the function on ng-submit

I have a function reset(username) that outputs whatever is entered into the input field of ng-model="username". Why is it not appearing in console though?
This is my function
$scope.reset = function (username) {
console.log(username);
};
and the way I submit the form
<form name="Form" ng-controller="ResetController" ng-submit="reset(username)">
<div>
<div class="row top5">
<label for="username">Username</label>
<div class="col-xs-4">
<input type="text" id="username" placeholder="" maxlength="255"
ng-model="username" required autofocus>
</div>
<div>
<div class="col-xs-5">
<button translate class="btn btn-secondary" type="submit">Reset</button>
</div>
</div>
</div>
</form>
Controller as requested
app.controller("ResetController", function ($scope) {
$scope.username='';
$scope.reset = function (username) {
console.log('username = ', username);
};
});
I believe you do have the ng-app and everything else besides this form, however it is better handled by the DOM if you manipulate your inputs as properties of an object and not directly as $scope. properties. See answers to this here. And note in the code how I attached username to $scope.object.username
var app = angular.module('myApp',[])
app.controller('ResetController',['$scope',function($scope){
$scope.object = {};
$scope.reset = function(username){
console.log(username);
};
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<form name="Form" ng-controller="ResetController" ng-submit="reset(object.username)">
<div>
<div class="row top5">
<label for="username">Username</label>
<div class="col-xs-4">
<input type="text" id="username" placeholder="" maxlength="255"
ng-model="object.username" required autofocus>
</div>
<div>
<div class="col-xs-5">
<button translate class="btn btn-secondary" type="submit">Reset</button>
</div>
</div>
</div>
</form>
</div>

angularjs 2 forms one page, one works, the other doesn't

I have no idea what I have done here.
I have this view:
<div class="row" ng-if="!controller.showLoginForm">
<div class="col-md-4 col-md-offset-4">
<form name="registerForm" ng-submit="controller.register(registerForm.$valid)" novalidate>
<div class="form-group" ng-class="{ 'has-error': registerForm.email.$invalid && !registerForm.email.$pristine }">
<label class="control-label">Email</label>
<input class="form-control" name="email" type="email" ng-model="controller.model.email" required />
<p ng-show="registerForm.email.$invalid && !registerForm.email.$pristine" class="help-block">Enter a valid email address.</p>
</div>
<div class="form-group">
<button class="btn-link navbar-btn" type="button" ng-click="controller.showLoginForm = !controller.showLoginForm">Not registered?</button>
<button class="btn btn-primary pull-right" type="submit" ng-disabled="registerForm.$invalid">Register</button>
</div>
</form>
<pre>{{ controller.model | json }}</pre>
</div>
</div>
<div class="row" ng-if="controller.showLoginForm">
<div class="col-md-4 col-md-offset-4">
<form name="form" ng-submit="controller.login(form.$valid)" novalidate>
<div class="form-group" ng-class="{ 'has-error': form.email.$invalid && !form.email.$pristine }">
<label class="control-label">Email</label>
<input class="form-control" name="email" type="email" ng-model="controller.model.email" required />
<p ng-show="form.email.$invalid && !form.email.$pristine" class="help-block">Enter a valid email address.</p>
</div>
<div class="form-group" ng-class="{ 'has-error': form.password.$invalid && !form.password.$pristine }">
<label class="control-label">Password</label>
<input class="form-control" name="password" type="password" ng-model="controller.model.password" ng-minlength="8" required />
<p ng-show="form.password.$error.minlength" class="help-block">Password is too short.</p>
</div>
<div class="form-group">
<button class="btn-link navbar-btn" type="button" ng-click="controller.showLoginForm = !controller.showLoginForm">Not registered?</button>
<button class="btn btn-primary pull-right" type="submit" ng-disabled="form.$invalid">Login</button>
</div>
</form>
<pre>{{ controller.model | json }}</pre>
</div>
</div>
The issue with this is that the login form works fine....validation and all...but the register form doesn't work at all.
ng-submit does nothing, none of the ng-class fire and ng-disabled doesn't work.
The controller looks like this:
(function () {
'use strict';
angular.module('widget.directives').controller('PkAuthenticateController', PkAuthenticateController);
PkAuthenticateController.$inject = ['pkAuthenticateService'];
function PkAuthenticateController(pkAuthenticateService) {
var self = this;
// Bindings
self.model = { email: '' };
self.showLoginForm = pkAuthenticateService.hasLogin;
// Method binding
self.register = register;
self.login = login;
//////////////////////////////////////////////////
function register(valid) {
if (valid) {
return pkAuthenticateService.register(self.model);
}
};
function login(valid) {
if (valid) {
return pkAuthenticateService.login(self.model);
}
};
};
})();
Can anyone spot what I have done wrong?

Angular JS textarea validation with required & showing error message

I have a Angular JS code where i want to implement validation and focus on the field back if textarea is empty.
<form ng-submit="addComment()" role="form" name="blogForm" novalidate>
<div class="form-group" ng-class="{ 'has-error' : blogForm.blogComment.$invalid && replySubmitted }">
<textarea ng-model="blogComment" name="blogComment" class="form-control" rows="3" ng-required="true" required></textarea>
</div>
<div style="color:#a94442;" ng-show="blogForm.blogComment.$invalid && replySubmitted">
<span ng-show="blogForm.blogComment.$error.required">Comment Text required.</span>
</div>
<button type="submit" ng-click="replySubmitted = true" class="btn btn-primary blog-bubmit-button">Submit</button>
</form>
For some reasons the above code is just inserting empty data and field is focused Invalid.
Any Suggestions may help me.
Thanku
you have define ng-app to process it as angular block.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app=''>
<form ng-submit="addComment()" role="form" name="blogForm" novalidate>
<div class="form-group" ng-class="{ 'has-error' : blogForm.blogComment.$invalid && replySubmitted }">
<textarea ng-model="blogComment" name="blogComment" class="form-control" rows="3" ng-required="true" required></textarea>
</div>
<div style="color:#a94442;" ng-show="blogForm.blogComment.$invalid && replySubmitted">
<span ng-show="blogForm.blogComment.$error.required">Comment Text required.</span>
</div>
<button type="submit" ng-click="replySubmitted = true" class="btn btn-primary blog-bubmit-button">Submit</button>
</form>
</div>

AngularJS Form validation Group error message

In angularJs FORM SUBMIT how to display all validation messagees in one single div at bottom of the page. Ex:
<div id="err-msg"> <!-- error message will come here --></div>
I referred documents but all are displaying below the text box using
<p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="alert alert-danger">Enter a valid email.</p>
How to write one area to bind all the messages in to same place (avoid use this userForm.email.$invalid)
Note I tried ng-message but am not clear any one help me. Please refer the below code for normal HMTL jQuery error display like need to take care using the AngularJS
HTML
<div id="main">
<form> <div><input id="email_txt" type="text" name ="email" value="" > </div>
<div><input id="pass_txt" type="password" name ="password" value="" > </div>
<div><input id="validate_btn" type="submit" value="Validate" > </div>
</form>
</div>
<div id="err-msg"> <!-- error message will come here --></div>
jQuery:
$('#main').on('click', '#validate_btn', function() {
if($('#email_txt').val().length == 0){
$('#err-msg').val("Please enter emailid!");
}else if($('#pass_txt').val().length == 0){
$('#err-msg').val("Please enter password!");
}
...
...
else{
alert("Good");
}
});
AngularJS current code :
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>
<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control" ng-model="user.username" ng-minlength="3" ng-maxlength="8">
<p ng-show="userForm.username.$error.minlength" class="help-block">Username is too short.</p>
<p ng-show="userForm.username.$error.maxlength" class="help-block">Username is too long.</p> </div>
<input type="email" name="email" class="form-control" ng-model="email">
<p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">Enter a valid email.</p>
<button type="submit" class="btn btn-primary">Submit</button>
<form>
app.js
.controller('validatectrl',['$scope',function($scope){
$scope.submitForm = function(isValid) {
// check to make sure the form is completely valid
if (isValid) {
alert('Good');
}
};
}]);
How to rewrite?
If a form is invalid, the errors will be stored in the object $scope.form.$error. Please check console of this JSFiddle. From the $error property on the form, you can populate the error messages.
angular.module('Joy', [])
.controller('FormCtrl', ['$scope', function ($scope) {
$scope.user = {};
$scope.submit = function () {
console.log($scope.userInfo);
};
}]);
The HTML:
<div ng-app="Joy" id="play-ground">
<form name="userInfo" novalidate ng-controller="FormCtrl">
<div class="ui input">
<input ng-model="user.email" ng-message="YOU ARE WRONG" name="User Email" type="email">
</div>
<div class="ui input">
<input ng-model="user.name" name="User Name" type="text" required>
</div>
<div class="ui divider"></div>
<button class="ui primary button" ng-click="submit()">Submit</button>
<div class="ui positive message">User: {{ user | json }}</div>
</form>
</div>

ngSubmit not getting submitted

I am pretty much beginner with AngularJS, and I am trying to submit a form, as follows:
<div ng-include="APP_URL + '/view/myResolver/searchForm.html'" ng-controller="MySearchFormController"> </div>
This is my searchForm.html:
<div class="container">
<div class="row">
<div class="col-md-14">
<div class="well">
<div class="col-md-9">
<form ng-submit="submit()" class="form-horizontal clearfix" role="form" >
<div class="form-group">
<label for="teamName" class="col-md-3 control-label">Team name</label>
<div class="col-md-9">
<input type="text" ng-model="myName" id="myName" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-0"></div>
<button ng-click="onFormReset()" class="btn btn-default">Reset</button>
<input type="submit" id="submit" class="btn btn-primary" value="Search"/>
</div>
</form>
{{teamName}}
</div>
</div>
</div>
UPDATE
Controller:
angular.module('MyApp')
.controller('MySearchFormController', ['$scope', function($scope){
$scope.submit = function (){
if ($scope.myName) {
alert($scope.myName);
$scope.teamName = this.teamName;
}
}
}]);
What is currently happening is the text is automatically appearing in the {{teamName}} field.
Instead, I would like to make it work only onSubmit(), namely clicking the Search button.
You can try like this :
function demo ($scope) {
$scope.submit = function () {
$scope.submitted = true;
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="demo">
<form ng-submit="submit()">
<input type="text" ng-model="teamName">
<button>Submit</button>
</form>
<p ng-if="submitted">{{ teamName }}</p>
</div>
BUT it is not optimal, as once you submitted one time, $scope.submitted is true and you will get the same problem, again.
SO, I would recommend you to not bind your {{ teamName }} to the same reference as the input :
function demo ($scope) {
$scope.submit = function () {
$scope.teamNameCopy = angular.copy($scope.teamName);
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="demo">
<form ng-submit="submit()">
<input type="text" ng-model="teamName">
<button>Submit</button>
</form>
<p>{{ teamNameCopy }}</p>
</div>
OK, the issue is resolved.
Unfortunately, that was an issue related to incorrectly closing html tags, and not

Categories