Prevent deleting string from textbox after reaching certain length in AngularJS - javascript

I want to prevent the user from deleting certain length of string from textbox in AngularJS.
I want some text like "abcd" to be fixed in textbox such that user cannot delete it. It would act like pre-string.
For that I have initialized the textbox with ng-init and on keyup event I'm checking the length of string, if it is less than predefined size then I'm putting the string back in the ng-model.
It's working with no errors, but not smoothly. I want to prevent pressing backspace or delete button if the text reached to specified length while deleting the text from textbox.
I am new to AngularJS.
Here is the Plunker link.
HTML
<body ng-app="myApp1">
<div ng-controller="myController">
<div ng-app>
<label>Key:</label>
<input type="text" name="key" ng-model="key" ng-init="key = 'abcd'" ng-keyup="updateKey($event)">
</div>
</div>
</body>
AngularJS
(function(angular) {
'use strict';
var myApp = angular.module('myApp1', []);
myApp.controller('myController', ['$scope', function($scope) {
$scope.updateKey = function($event) {
var len = $scope.key.length;
if ($event.keyCode === 8 && len < 4) {
$scope.key = "abcd";
}
};
}]);
})(window.angular);

I think you can setup a explicit $watcher function for the $scope.key
$scope.$watch('key', function(newValue, oldValue) {
console.log(oldValue, newValue);
if(newValue.length < 4) {
$scope.key = 'abcd';
}
});
watcher function will call every time when the model is change, so when you change the model angular will call this function, in the function we can get the old value and new value based on that you can do what you try to achive.
here is the DEMO

Related

custom filter for hiding the negative values

I have a text box, I want to show nothing in the text box if the ng-model contains negative value, and I want to leave ng-model as it is. And it should not display the data if the data is negative value,If the value is negative then I want to show the empty in text box, but the ng-model should contain that negative value. I need a custom filter to achieve this functionality
Plunker
<input type = "text" ng-model="number"></input>
Filters can be added in AngularJS to format data.
Now, if you are thinking to 'bind' ngModel with the text-box and want to apply filter on it (i.e. markup: <input ng-model="number | nonNegative" />), try-it yourself, you'll get the below error, when you check it in fiddle
Error: Non-assignable model expression: number | nonNegative ()
When you want to show the values are below, using filter, you'll be able to do so.
angular.module('myApp', [])
.controller('LoginController', function ($scope) {
$scope.number = -10;
$scope.number1 = -20;
$scope.number2 = 30;
})
.filter('nonNegative', function(){
return function(val){
if(val >= 0) return val; else '';
}
})
HTML:
Number: {{number | nonNegative}}
<br/>
Number1: {{number1 | nonNegative}}
<br/>
Number2: {{number2 | nonNegative}}
----EDIT-----
Even when you use $watch, the actual value will be different and the value in the textbox will be different.
Check this fiddle
angular.module('myApp', [])
.controller('LoginController', function ($scope) {
$scope.number1 = -20;
$scope.$watch('number1', function(newVal, oldVal) {
if(newVal < 0) newVal = '';
})
})
HTML
<div ng-app="myApp" ng-controller="LoginController">
<input type = "text" ng-model="number1" />
<input type="submit" ng-click="login()" value="Login" />
<br/>
Number1: {{number1 | nonNegative}}
</div>
The number field is having no value, as you see in the fiddle, but still the textbox displays negative value

How to reset all Models on click event?

My requirement: Have to reset my select boxes on button click
Example :-
I have 3 select boxes. When I click on the select box some different data will come and after that the result will get published. I added a Remove button which resets only its parent select box. Now, what I want to know is,how to reset all the three select box on clicking the remove button.
sample code is as under :-
<button ng-click="removeObj(key,model1,0)">Remove</span></button>
controller code is as under :-
scope.removeObj = function(modelID, subModelID, selectBoxPos) {
modelID = 0;
subModelID = 0;
})
I want on click of removeObj function all modelID data get reset to zero.
Please help.
As I understand you do not need any parameters.. only create a meaningful name resetModels:
AngularJS Controller:
$scope.resetModels = function() {
// Set default value to your models...
$scope.modelID = 0;
$scope.subModelID = 0;
});
Html:
<button ng-click="resetScpeModels()">Remove</span></button>
If you want to reset all the values. You should use it like this
$scope.model = {};
$scope.model.modelID = 0;
$scope.model.subModelID = 0;
<input ng-model="model.modelID"/>
If you want to reset it. Call again
$scope.model = {};
Inside ng-click function.
When you give a name to your form it automatically gets added to the $scope.
In angular we are having a $setPristine() method on the $scope.formName. which should recursively take care of resetting your form.
You can reset a form by, $scope.formName.$setPristine(); but if you're binding a model object to your inputs, you need to take care of clearing those too, ie:
$scope.formModel={}; or angular.copy({}, formModel);
Working demo :
var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
$scope.Reset = function(formModel) {
angular.copy({}, formModel);
$scope.formModel = {};
$scope.submitForm.$setPristine();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<form name="submitForm" ng-controller="myController">
<label for="first_field">First Model</label>
<input ng-model="formModel.firstModel" />
<br />
<label for="second_field">Second Model</label>
<input ng-model="formModel.secondModel" />
<br />
<button type="button" ng-click="Reset(formModel)">Reset</button>
</form>
</div>

angular trimmed input value

I've got some issues with ng-model and input element. Please take a look at this plunker: http://plnkr.co/edit/PJCv1AsPns1cxuSPTZiU
My point is when I edit the input value and add some white spaces at the beginning and at the end f.e.
some text
and click save the white spaces are trimmed (and it's OK) from inputValue, but if I edit it again the "previous" white spaces appear in the input. How to prevent it? I tried to do this with
angular.element($('#trimInput')).val($scope.inputValue);
and it works, but I don't like this solution.
angular.module('app', [])
.controller('trim', ['$scope', function($scope) {
$scope.inputValue = "some text";
$scope.editMode = false;
$scope.edit = function() {
$scope.editMode = true;
};
$scope.save = function() {
$scope.editMode = false;
//angular.element($('#trimInput')).val($scope.inputValue);
console.log($scope.inputValue);
console.log($scope.inputValue.length);
};
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
<div ng-controller="trim">
<div ng-show="!editMode">
[{{inputValue}}]
<button ng-click="edit()">edit</button>
</div>
<div ng-show="editMode">
<input id="trimInput" type="text" ng-model="inputValue" />
<button ng-click="save()">save</button>
</div>
</div>
</body>
By default ng-trim is true in angular so it will automatically trim value in scope. But value will not update on input, means extra input will be there. You have to manually assign it.
$document[0].getElementById("trimInput").value = $scope.inputValue;
For this you need to inject $document in your application. This is automatically assign trim value to input when you save.
See DEMO
Use
var temp=document.getElementById('trimInput');
console.log(temp.value);
$scope.inputValue=temp.value
and
Why is this Angular JS filter removing spaces?

How to display validation errors for array form fields in AngularJS?

I created a dynamic form where there are repeated fields submitted as an array. However, i want to validate each field individually and display the error message next to it. If i only have one row, it works fine, but once i add a second row, the first row stops displaying errors.
<form name='user' id='user' novalidate>
<div ng-repeat="bonus in bonuses">
<input name='codes[]' ng-model="bonus.code" lower-than="{{bonus.end_code}}" />
<input name='end_codes[]' ng-model="bonus.end_code" />
<span class="text-error" ng-show="user['codes[]'].$error.lowerThan">
Code must be less than End Code.
</span>
</div>
</form>
AngularJS
var app = angular.module('newBonus', []);
app.controller('NewBonusController', function($scope) {
$scope.bonuses = [];
$scope.addFields = function () {
$scope.bonuses.push({code:'', end_code: ''});
}
$scope.submit = function(){
console.log($scope.bonuses);
}
});
// Validate that one field is less or equal than other.
app.directive('lowerThan', [
function() {
var link = function($scope, $element, $attrs, ctrl) {
var validate = function(viewValue) {
var comparisonModel = $attrs.lowerThan;
if(!viewValue || !comparisonModel){
// It's valid because we have nothing to compare against
ctrl.$setValidity('lowerThan', true);
}
// It's valid if model is lower than the model we're comparing against
ctrl.$setValidity('lowerThan', viewValue <= comparisonModel );
return viewValue;
};
ctrl.$parsers.unshift(validate);
ctrl.$formatters.push(validate);
$attrs.$observe('lowerThan', function(comparisonModel){
return validate(ctrl.$viewValue);
});
};
return {
require: 'ngModel',
link: link
};
}
]);
plunker: http://plnkr.co/edit/Fyqmg2AlQLciAiQn1gxY
I can settle for not having it next to each field, as long as changes to other field sets does trigger the error message properly in which case i can just pop it at the top. The main issue i see is that because they're arrays codes[] which are passed to the form at the end, they will not work properly.
The submit button is disabled properly on form validation, so i'm not sure why the message only locks onto the last row added.
Use a child form to separate the scope.
<ng-form name="frmChild">
<input name='codes' ng-model="bonus.code" lower-than="{{bonus.end_code}}" />
<input name='end_codes' ng-model="bonus.end_code" />
<span class="text-error" ng-show="frmChild.codes.$error.lowerThan">
Code must be less than End Code.
</span>
</ng-form>

Trying to update one input's value to another's using angularjs

I'm fairly new using AngularJS but I've been using for a pet project and I've run in to an issue. What I basically want to do is take the text input from this input field:
<form id="ci_search_form">
<p class="input-append"><label>Search:</label> <input type="text" id="query" ng:model="query" autofocus> <button ng:click="clearSearch()" class="btn"><i class="icon-remove"></i></button></p>
</form>
and update this input field's value with that value:
<div><input type="text" id="ciquery" ng:model="ciquery.Name"></div>
The second input filters some data and I can type in that directly and it works. However this page will have different sets of data, each with their own search input that I want updated by the master input at the top. I can't set value="" or use jQuery to set the value either, it just appears blank unless I explicitly type in that second input field. Can anyone assist with a solution?
EDIT
I thought I should include my app and controller code:
var App = angular.module('TicketAssistApp', []);
App.controller('SearchController', function($scope, $http, $filter){
$scope.query = '';
$http.get('static/ci_list.json').success(function(data){
$scope.ci_list = data;
});
$scope.clearSearch = function(){
$scope.query = '';
}
});
EDIT 2
Made some progress. Created a function that can be called an update ciquery in $scope:
var App = angular.module('TicketAssistApp', []);
App.controller('SearchController', function($scope, $http, $filter){
$scope.query = '';
$scope.ciquery = '';
$http.get('static/ci_list.json').success(function(data){
$scope.ci_list = data;
});
$scope.queryUpdate = function(){
$scope.ciquery = $scope.query;
}
$scope.clearSearch = function(){
$scope.query = '';
$scope.queryUpdate();
}
});
This works great. However, this creates another issue. Before in ciquery I was using ciquery.Name to filter only on the Name attribute. With this new solution I had to change it to this:
<div><input type="hidden" id="ciquery" ng:model="ciquery"></div>
This searches all fields in my data which returns unwanted results. Suggestions?
$scope and ng-model are differents. You should give ng-model's property to ng-click's function. Looks at this -> Ng-model does not update controller value
To update second input's field (here an example -> http://jsfiddle.net/yEvSL/1/)
<div><input type="text" id="ciquery" ng:model="query"></div>

Categories