Disable Text Entry - angular with jquery - angularjs

Found these perfect solution here: Example
// Catch all events related to changes
$('#textbox').on('change keyup', function () {
// Remove invalid characters
var sanitized = $(this).val().replace(/[^-.0-9]/g, '');
// Remove non-leading minus signs
sanitized = sanitized.replace(/(.)-+/g, '$1');
// Remove the first point if there is more than one
sanitized = sanitized.replace(/\.(?=.*\.)/g, '');
// Update value
$(this).val(sanitized);
});
HTML
<input type="text" id="textbox" />
but i can't make this work inside a controller.
How can it be done?

One thing that you can do is use ng-change in your input like this:
<div ng-controller="yourCtrl as ctrl">
<input type="text" id="textbox" ng-change="ctrl.doSomething()" ng-model="ctrl.someVar">
</div>
in this way you will have access to the value of the input inside your controller that can be like this:
angular.module('yourModule').controller('yourCtrl',[function(){
var self = this;
self.doSomething = function(){
//you can access the value of the input using
// self.someVar
}
});
The ng-change (official doc: https://docs.angularjs.org/api/ng/input/input%5Btext%5D ) is "executed when input changes due to user interaction with the input element".
You can also use the ngKeyup (official doc: https://docs.angularjs.org/api/ng/directive/ngKeyup ) that is "evaluated upon keyup" how you connect it to a function is the same as ng-change. You will have only to choose one of the two.

Related

Get value from input type email with Angular

How can I pass the value of an <input type='email'> using angularjs. I need to validate the email address on the input of my form and need to generate a key with this. The only thing I need to know is how should I get the value from the input.
angular.module('myApp', [])
.controller('EmailController', function($scope) {
$scope.hash = "";
$scope.generateKey = function () {
var resultKey = $scope.email;
// TODO: generate key
// Assing value to hash
$scope.hash = resultKey;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="EmailController">
<form>
<p>Email: <input type="email" ng-model="email" ng-keyup="generateKey()"></p>
<p><b>Hash: </b>{{hash}}</p>
</form>
</div>
Edit 1
I could use <input type='text'> and validate with a regex but I want to use type='email' as in the cellphone display more options on the keyboard. Does exist a way to get the input value using angular even if it isn't a valid email?
Use ng-model-options="{ allowInvalid: true }" if you want invalid email addresses to be bound to your controller:
<input type="email" ng-model="email" ng-keyup="generateKey()" ng-model-options="{ allowInvalid: true }">
Edit: You usually shouldn't data-bind to a primitive because prototypal inheritance can sometimes lead to binding to the wrong scope. Try binding to an object instead, like data.email.
Edit: Live example
The way angular handles input values and validations is via $parsers. you can intercept the default parsers and therefore get the value before it get to the email validation. Created this little snippet to further illustrate my point. Notice that I am not using .push to add my parser but instead I am using .unshift. I use unshift rather than push because I want to make sure my parser is the first on the list. or at least, the first at the moment i added to the list. This will guarantee that it runs before the default parsers which are already in the list by the time my code runs.
var app = angular.module('myApp', []);
app.controller('EmailController', function($scope) {
$scope.hash = "";
});
app.directive('generateKey', function(){
return {
require: ['ngModel'],
link: function(scope, element, attr, ctrls){
var ngModel = ctrls[0];
ngModel.$parsers.unshift(function(text){
scope.hash = text;
return text;
});
}
};
});
for a complete snippet, please visit: https://jsbin.com/vabofapigo/edit?html,js,output

Why I cannot access form angular's properites in JS such as $error?

I cannot access angular's Form members. I don't have a clue why. I'm using angular 1.4. The full code is at: http://jsbin.com/lujojiduru/edit?html,js,console,output
angular.module('test',[]).controller('testController', function($scope){
$scope.sendInvitations = function(){
var error = myForm.NewInvitations.$error;
console.log('sent');
console.log('value: ' + error );
};
});
the value of $error is always undefined. Any idea?
var error = myForm.NewInvitations.$error;
should be:
var error = $scope.myForm.NewInvitations.$error;
Notice the $scope
This is assuming you have the name="myForm" on your <form> tag
So something like:
<div ng-controller="testController">
<form name="myForm" novalidate>
...
</form>
</div>
you can also, if you prefer, send in the validity of your form, to your method on the controller.
So:
<button class="btn btn-success" ng-click="sendInvitations(myForm.$valid)">Send Invitations</button>
And in your controller:
$scope.sendInvitations = function(isValid){
if(!isValid)
return;
};
Update
You also don't have any errors.
Add required to your input.
So your controller is now:
angular.module('test',[]).controller('testController', function($scope){
$scope.sendInvitations = function(){
debugger;//
var error = $scope.myForm.NewInvitations.$error;
console.log('sent');
console.log(error );
};
});
and your input
<input style="width: 95%" name="NewInvitations" type="email" ng-model="newInvitations" required />
This is an update to your bin
http://jsbin.com/hebikucanu/1/edit?html,js,console,output
myForm is not accessible in the global scope. You can pass it in as an argument to sendInvitations.
ng-click="sendInvitations(myForm)
$scope.sendInvitations = function(myForm){
It's unlikely that you'd need to do this, though. You can do use the myForm properties in the view.
In angular, you should never touch the DOM. Meaning, you should never invoke HTML elements directly as you would in traditional HTML/JS settings. (read more)
Angular encourages the use of ng-model to employ two-way binding as a means to communicate between the controller and the view. (angular two-way data binding tutorial)
Thus, the first change you should attempt is to replace
var error = myForm.NewInvitations.$error;
with:
var error = $scope.NewInvitations;
This will cause the code to run.
But it appears that you want to retrieve the email input validation error and display it through angular.
Here is an excellent explanation with a tutorial that I think achieves what you're trying to do. If you just want to see the code in action, try this link. (Be sure to hit the Run button.)
Hope this helps!

angularjs ng-paste not updating model value

I have used ng-paste for textarea while pasting the link in textarea, i am calling a custom function to store that value. Please refer following code
<textarea rows="1" ng-model="myObj.content"
ng-paste="getContent(myObj)">
</textarea>
$scope.getContent = function(a){
console.log(a.content);
}
But in console always I am getting undefined value. How can I get my object value?
Passing model to function does not really make sense since you have already specified ng-model, so it's value will be updated as user types something into the textbox. If you want to track changes you can setup a $watch for your model or specify a function using ng-change.
If you want to know what user pasted, then that's another story. Handling ng-paste can be tricky. To access the actual event, easiest is to include jQuery before angularjs and then do e.g. following:
HTML template
<textarea rows="3"
placeholder="copy/paste here..."
ng-init="content = null"
ng-model="content"
ng-paste="paste($event.originalEvent)">
</textarea>
Controller
$scope.paste = function (event) {
var item = event.clipboardData.items[0];
item.getAsString(function (data) {
console.log(data);
});
};
Related plunker here http://plnkr.co/edit/ea5y5j
Simply use $timeout to call your paste callback after the model has been updated.
$scope.getContent = function(a){
$timeout(function () {console.log(a.content)});
}

angularjs - undefined error from input text field

Trying to initialize text input box for user input but getting error. $scope can set intext when uncommentted. I've hacked around this (sort of) but I'm missing something basic as usual.
Console error starts: 'Error: $scope.intext is undefined' unless I assign a value. The input box is exclusively for user input. Also noticed I can assign 'why' and don't get the error until I try to split.
angular.module('myApp', [])
.controller('TextScreen', ['$scope', function($scope) {
//$scope.intext = "what";
var why = $scope.intext.split('-');
}]);
html
<div id="cont" ng-app="myApp">
<div ng-controller="TextScreen">
<input type="text" ng-model="intext" />
</div>
</div>
The reason is that $scope.intext is undefined. intext.
It is unclear what you are trying to do but I would suggest initializing intext or moving your code to a function. Like this:
$scope.change = function() {
var why = $scope.intext.split('-');
};
html
<input type="text" ng-model="intext" ng-change="change()" />
Like suggested in angular documentation here:
http://docs.angularjs.org/api/ng.directive:ngChange
Or try using ng-init
ng-init="intext= 'demo'"
Sample
<input type="text" ng-model="intext" ng-init="intext= 'demo'" />
O
The
var why = $scope.intext.split('-');
is being processed immediately, but at that moment, $scope.intext is undefined, therefore you cannot call .split on it.
If you are trying to act on the value the user enters, you should place a watch on it
$scope.$watch('intext', function(oldvalue, newvalue){
if(angular.isDefined(newvalue) && newvalue != oldvalue) //ensuring undefined should not processed
var why = newvalue.split('-');
});

AngularJS calculated ng-model

I have following controller.
app.controller("testCtrl", function(){
$scope.utcTime = 1380150771;
$scope.parseTime = function(t){
//return local time string
}
});
In the view, I have
<input type="text" ng-model="parseTime(utcTime)" />
Its not working. Can I bind ng-model to a method that returns the string ?
Any alternative way to show the value in the input button ?
You can use ngChange and ngModel both
JS
$scope.utcTime = 1380150771;
$scope.parseTime = function(){
console.log($scope.utcTime);
//return local time string
}
HTML
<input type="text" ng-change="parseTime()" ng-model="utcTime" />
ng-model is mapping through tag and controller.
At first you can see default utcTime (1380150771) that you assign in input tag.
And when you change the text in input tag, ng-model(utcTime) will be changed automatically in the controller.
Then each letter that you typed will call ng-change(parseTime) function.
You can check by console.log method.
My solution is based on this source:
https://groups.google.com/forum/#!topic/angular/1mnra0vamtg
I have edited the Plunker sample code to use ng-value to generate and update ng-model using calculation function. See this link below:
http://plnkr.co/edit/Fmqw0wp37Ndk1yuWvFkV?p=preview
Also, the above sample shows you how you format the result for display using custom filter.
In other posts, some have suggested using $watch() to detect change to input variables and update ng-model variable accordingly. Using ng-value is much better than using $watch() since the latter forces you to include all input variables in the watch which may be impossible if you have very complex calculation model.
Tarek
Try doing this
app.controller("testCtrl", function(){
$scope.utcTime = 1380150771;
$scope.result= $scope.parseTime( $scope.utcTime)
$scope.parseTime = function(t){
//return local time string
}
});
html
<input type="text" ng-model="result" />
Yes you can try follwing:
its working example:
<input type="text" ng-model="parseTime(utcTime)" />
app.controller("testCtrl", function(){
$scope.utcTime = 1380150771;
$scope.parseTime = function(t){
//return local time string
new Date(t).toISOString();
}
});

Resources