angular removes ng-model variable if ng-required is true - angularjs

as in the title.. how to prevent such operations to happen? Here is a link to the official site, see the example. The variable user.name is bound to the first input userName and if the input is empty the object user.name is removed. How can I disable this functionality of angularjs?

Try ng-model-options="{allowInvalid: true}" to update the model even for invalid entries.
<input ng-model="user.name" required ng-model-options="{allowInvalid: true}">

You've got 2 option
remove required from input tag it allows you to send back empty string to your backend
var app = angular.module('app', []);
app.controller('MyCtrl', function($scope) {
$scope.params = {
user: "John"
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MyCtrl">
<input name="userName" ng-model="params.user" />
<hr/>
<pre>{{params| json}}</pre>
</div>
Option two validate your form before you send it to backend.
var app = angular.module('app', []);
app.controller('MyCtrl', function($scope) {
$scope.user = {
name: "John"
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MyCtrl">
<form name="someForm">
<input name="userName" ng-model="user.name" required name="userName" />
<span ng-show="someForm.userName.$error.required">User Name required</span>
<br/>{{user | json}}
<br/>
<button type="submit" ng-disabled="someForm.$invalid">Submit</button>
</form>
</div>

Related

Writing an adding function in AngularJS

I'm new to AngularJS and I am doing some tutorials to get in touch with it. While I'm doing the tutorials I have modified the code a bit to get a better feeling of what's behind. My code consists of two parts, which have nothing to do with each other.
The first one is a simple user input and based on that a list gets filtered. This is working fine.
However, in the second part I was trying to implement a simple adding function where the user can give an input and based on that the sum of two numbers is calculated. This part is not working at all. The numbers are being recognised as strings. The code is basically from this source here. When I copy the whole code and run it, it works fine, but when I modify it a bit it doesn't.
I want to understand why my code isn't working. To me there is nearly no difference. So I think that I eventually misunderstood the concept of angularjs. But I can't figure out where the error could be.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script type="text/javascript">
function TodoCtrl($scope) {
$scope.total = function () {
return $scope.x + $scope.y;
};
}
</script>
</head>
<body data-ng-app>
<input type="text" ng-model="name">{{name}}
<div data-ng-init="Names=['Arthur', 'Bob', 'Chris', 'David', 'EDGAR']">
<ul>
<li data-ng-repeat="naming in Names | filter: name ">{{naming}}</li>
</ul>
</div>
<div data-ng-controller="TodoCtrl">
<form>
<input type="text" ng-model ="x">{{x}}
<input type="text" ng-model ="y"> {{y}}
<input type="text" value="{{total()}}"/>
<p type= "text" value="{{total()}}">value</p>
</form>
</div>
</body>
</html>
Several things to change...
First you need to create a module:
var app = angular.module("myApp", []);
Then you need to define a module e.g. myApp on the ng-app directive.
<body data-ng-app="myApp">
Then you need to add TodoCtrl to the module:
app.controller("TodoCtrl", TodoCtrl);
Also check that both $scope.x and $scope.y have values, and make sure that they are both parsed as integers, otherwise you will get string concatenation ("1"+"1"="11") instead of addition (1+1=2)!
$scope.total = function () {
return ($scope.x && $scope.y)
? parseInt($scope.x) + parseInt($scope.y)
: 0;
};
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script type="text/javascript">
(function(){
var app = angular.module("myApp", []);
app.controller("TodoCtrl", TodoCtrl);
function TodoCtrl($scope) {
$scope.total = function () {
return ($scope.x && $scope.y)
? parseInt($scope.x) + parseInt($scope.y)
: 0;
};
}
}());
</script>
</head>
<body data-ng-app="myApp">
<input type="text" ng-model="name">{{name}}
<div data-ng-init="Names=['Arthur', 'Bob', 'Chris', 'David', 'EDGAR']">
<ul>
<li data-ng-repeat="naming in Names | filter: name ">{{naming}}</li>
</ul>
</div>
<div data-ng-controller="TodoCtrl">
<form>
<input type="text" ng-model ="x">{{x}}
<input type="text" ng-model ="y"> {{y}}
<input type="text" value="{{total()}}"/>
<p type= "text" value="{{total()}}">value</p>
</form>
</div>
</body>
</html>
As mentioned in the above two answers adding TodoCtrl as controller instead function will make the snippet work.
REASON:
Angularjs framework above 1.3 does not support global function which means declaring controller as function wont work.
In your code snippet, you are using angular version 1.5, which needs the controller to be defined.
DEMO
angular.module("app",[])
.controller("TodoCtrl",function($scope){
$scope.x = 0;
$scope.y = 0;
$scope.total = function () {
return parseInt($scope.x) + parseInt($scope.y)
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" >
<input type="text" ng-model="name">{{name}}
<div data-ng-init="Names=['Arthur', 'Bob', 'Chris', 'David', 'EDGAR']">
<ul>
<li data-ng-repeat="naming in Names | filter: name ">{{naming}}</li>
</ul>
</div>
<div data-ng-controller="TodoCtrl">
<form>
<input type="text" ng-model ="x">{{x}}
<input type="text" ng-model ="y"> {{y}}
<input type="text" value="{{total()}}"/>
<p type= "text" value="{{total()}}">value</p>
</form>
</div>
</div>
you need to define the TodoCtrl as controller instead function
.controller("TodoCtrl",function($scope){
$scope.x = 0;
$scope.y = 0;
$scope.total = function () {
return parseInt($scope.x) + parseInt($scope.y)
};
})
Demo
angular.module("app",[])
.controller("TodoCtrl",function($scope){
$scope.x = 0;
$scope.y = 0;
$scope.total = function () {
return parseInt($scope.x) + parseInt($scope.y)
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" >
<input type="text" ng-model="name">{{name}}
<div data-ng-init="Names=['Arthur', 'Bob', 'Chris', 'David', 'EDGAR']">
<ul>
<li data-ng-repeat="naming in Names | filter: name ">{{naming}}</li>
</ul>
</div>
<div data-ng-controller="TodoCtrl">
<form>
<input type="text" ng-model ="x">{{x}}
<input type="text" ng-model ="y"> {{y}}
<input type="text" value="{{total()}}"/>
<p type= "text" value="{{total()}}">value</p>
</form>
</div>
</div>

Should not allow the space in password field?

Need to show error message whenever i enter space in password input field using ng-pattern.
Use of regEx - /^\S*$/ does not allow space anywhere in the string.
<form name="myForm">
<input type='password' name="passInpt" ng-model='pass' data-ng-pattern="/^\S*$/">
<div data-ng-show="myForm.passInpt.$error.pattern" >White Space not allowed</div>
</form>
DEMO:
var app = angular.module("app", []);
app.controller("ctrl", function($scope) {});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app" ng-controller="ctrl">
<form name="myForm">
<input type='password' name="passInpt" ng-model='pass' data-ng-pattern="/^\S*$/">
<div data-ng-show="myForm.passInpt.$error.pattern">White Space not allowed</div>
</form>
</body>
Here is the link Jsfiddle demo
You can check for indexof or you can use regX for it.
HTML
<div ng-app="myApp">
<div ng-controller="ctrl">
<form>
<span>{{error}}</span>
<input type='password' ng-model='pass' ng-change='check()'>
</form>
</div>
</div>
**JS **
var app = angular.module('myApp', []);
app.controller('ctrl', function($scope) {
$scope.error = '';
$scope.check = function() {
$scope.pass.indexOf(' ') > -1 ? ($scope.error = 'Invalid') : ($scope.error = '');
}
})
Hope this will help you
updated for space

Angular JS dropdown list select "Others" option and Others input become mandatory

I am trying to add a dropdown list with "Others" option. If user select "Others", Others (Please specify) input box will become Mandatory. How should I validate this case? Right now I added Javascirpt code to valid this. Is there anyway to do this like "Please specify other reason."?
<form name="myForm">
<div ng-app="myApp" ng-controller="myCtrl">
Reason : <select ng-model="reason" ng-options="x for x in names" required></select> <span ng-show="myForm.reason.untouched">The reason is required.</span>
<p>Others (specify): <input type="text" ng-model="others"></p>
</div>
</form>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["reason1", "reason2", "reason3","Others"];
$scope.addItem = function () {
if ($scope.reason == "Others" && !$scope.others)
{
window.alert("Please specify others");
}
if($scope.others && $scope.reason!='Others')
{
window.alert("Please select reason others");
}
});
</script>
Angular has an ng-required property that allows you to set it conditionally.
<form name="myForm">
<div ng-app="myApp" ng-controller="myCtrl">
Reason : <select ng-model="reason" ng-options="x for x in names" required>
</select> <span ng-show="myForm.reason.untouched">The reason is required.
</span>
<p>Others (specify): <input type="text" ng-model="others" ng-required="reason == 'Others'"></p>
</div>
</form>

if statement in angularjs is not working

i have a login page which evaluates username and password using angularjs
but it seems that my conditional statement in the controller returns false even if i put a true value
here's my html file
<div class="row">
<form action="/">
<input type="text" class="form-control" id="username" ng-model="username" required>
<input type="Password" class="form-control" id="username" ng-model="password" required>
<br>
<button type="button" style="width: 40%;" ng-click="submit()"> Log In </button>
</form>
</div>
and my controller
var app = angular.module('myApp', ["ngRoute"]);
app.controller('ctrl',
function($scope, $location) {
$scope.submit = function() {
var username = $scope.username;
var password = $scope.password;
if($scope.username == 'admin' && $scope.password == 'admin') {
console.debug('success');
} else {
console.debug('fail');
}
}
});
every time i input 'admin' in username and password i always get 'fail' in my console which means the submit function returns false . .
1) Per the HTML spec you need to cannot have the same id on 2 different elements
html 4.1
2)You should explicitly declare the objects you want your control to have injected like below. That way when you minifiy your code, the Dependency injection will continue to work
app.controller('ctrl',['$scope','$location'
function($scope, $location) { }]);
3) TO answer your question why isnt this working. My plunkr works. I removed the routing, because it wasnt needed. Make sure you are typing in 'admin' no spaces/caps
<html>
<head>
<script src="angular.js"></script>
<script src="route.js"></script>
</head>
<body>
<div class="row" ng-app="myApp" ng-controller="ctrl">
<form action="/">
<input type="text" class="form-control" id="username" ng-model="username" required>
<input type="Password" class="form-control" id="username" ng-model="password" required>
<br>
<button type="button" style="width: 40%;" ng-click="submit()"> Log In </button>
</form>
</div>
<script>
var app = angular.module('myApp',["ngRoute"]);
app.controller('ctrl',
function($scope, $location) {
$scope.submit = function() {
var username = $scope.username;
var password = $scope.password;
if($scope.username == 'admin' && $scope.password == 'admin') {
console.debug('success');
} else {
console.debug('fail');
}
}
});
</script>
</body>

validate dynamic form before submitting angular

I'm dynamically creating forms with ng-repeat and they have some validation attributes (simplified version):
<div class="row" ng-repeat="defect in model.defects">
<form name="form_{{defect.id}}" novalidate>
<input ng-model="defect.name" required/>
<input type="submit" ng-click="saveDefect(defect)"/>
</form>
</div>
Basically what I want to do is this:
$scope.saveDefect = function (defect) {
if ($scope.<how to get the form name here>.$invalid) {
return;
}
}
Since the form name has been created dynamically with an id how do I access it? Other ways of doing the same are also welcome ofcourse :)
You can use the bracket notation to access it :
$scope["form_"+defect.id]
What I advise you to do is :
var app = angular.module("App", []);
app.controller("Ctrl", function($scope) {
$scope.forms = {};
$scope.list = [{id: 1}, {id: 2}];
$scope.save = function(item) {
if ($scope.forms["form_" + item.id].$invalid) {
alert("error on form_" + item.id);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="App" ng-controller="Ctrl">
<div class="row" ng-repeat="item in list">
<form name="forms.form_{{item.id}}" novalidate>
<input ng-model="item.name" required/>
<input type="submit" ng-click="save(item)" />
</form>
</div>
</body>

Resources