Function is not defined ReferecenError onchange in Angularjs - html

I'm having issues with onchange event for file input.
Here is my code:
Html:
<input type="file" kendo-upload k-options="uploadOptions" id="fileInput" onchange="fileUploaded(event)"/>
Angularjs code - using Typescript.
$scope.fileUploaded = (event) => {
console.log("Testing file upload");
var reader = new FileReader();
var target = event.target || event.srcElement;
reader.onload = function(e) {
$scope.$apply(function() {
$scope.readFile = reader.result;
});
};
var file = target.files[0];
reader.readAsText(file);
};
I tried to follow this and change accordingly but am still having issues.
Pass angularJS $index into onchange
I changed like this.
<input type="file" kendo-upload k-options="uploadOptions" id="fileInput" onchange="angular.element(this).scope().fileUploaded(this)">
I got this error.
Uncaught TypeError: undefined is not a function.
onchange
When I am trying to use ng-change, I have this error.
<div kendo-window="importFile" k-visible="false" k-modal="true" k-title="'Import File'"
k-min-width="450" k-max-width="450"
k-min-height="418" k-max-height="418">
<form kendo-validator="validator" ng-submit="validate($event)">
<li style="padding-bottom: 5px;">
<input type="file" kendo-upload k-options="uploadOptions" id="fileInput" ng-change="fileUploaded($event)"/>
</li>
</form>
</div>
This gives error when accessing this
$scope.importFile.center();
"TypeError: Cannot read property 'center' of undefined"
Again, works fine if I use ng-click.
Any help on this is higly appreciated.
Thanks!

You cannot use ngChange in this case since ngChange always requires ngModel and ngModel doesn't work with input type file. Also, you cannot access a function binded to $scope directly using onchange. Instead use the following:
onchange="angular.element(this).scope().fileUploaded($event)"

Related

accessing angularjs textbox value in a controller

I am trying to learn AngularJS and require help in passing user entered text box text value after button click to append to a string url value while calling the http service.
I'm trying to add in the following way but it is showing me a value of undefined while appending the URl with the user entered text from the text box.
Here is my HtmlPage1.html
<form ng-submit="abc(inputValue)">
<input type="text" name="name" ng-model="inputValue" />
<button type="submit">Test</button>
</form>
and my script file Script.js
var app = angular.module("repos", [])
.controller("reposController", function ($scope, $http, $log) {
$scope.inputValue = null;
$scope.abc = function (value) {
$scope.inputValue = value;
};
$http({
method:'GET',
url: 'https://api.github.com/users/'+$scope.inputValue+'/repos'
})
.then(function (response) {
$scope.repos = response.data;
$log.info(response);
});
});
Can anyone help me in this regard on how to get the right value that the user has entered to appended to the URL?
Thanks in advance.
Your get call is placed before you enter any value. In order to call the API with inputValue, place the get call inside the button click.
Also, you do not have to pass the inputValue into the function from HTML, Angular's 2 way binding will do the job for you.
Ex:
HTML
<form ng-submit="abc()">
<input type="text" name="name" ng-model="inputValue" />
<button type="submit">Test</button>
</form>
JS:
var app = angular.module("repos", [])
.controller("reposController", function ($scope, $http, $log) {
$scope.inputValue = null;
$scope.abc = function () {
$log.info($scope.inputValue) // you will have your updated value here
$http({
method:'GET',
url: 'https://api.github.com/users/'+$scope.inputValue+'/repos'
})
.then(function (response) {
$scope.repos = response.data;
$log.info(response);
});
});
};
I hope this helps.
Just remember that you have the code on your controller thanks to 2 way binding.
There you will set up an object for models. Ad later you can use them to submit data.
In order for you to understand what I am trying to explain I made an example, I hope it Helps
In your code:
Set the ng-model on the input tag
<input type="text" name="name" ng-model="vm.data.inputValue" />
On your controller make it available as in my example
vm.data ={};
Then use a function to send it using ng-click.
<button type="submit" ng-click="vm.submit()">Test</button>
I am sure there are more ways to do this.
I am not that good, explaining so I made an example, that I hope helps:
https://jsfiddle.net/moplin/r0vda86d/
my example is basically the same but I prefer not to use $scope.

Angularjs form submit, url as action iframe as target

I am trying to do a form submit which has url as the action and target as iframe. I am getting the action url via an API call. If I hard coded the url in the controller it will work fine. But if i get the url from an API, click on the submit button will do nothing. What could be the problem here. Code is like following code snippets.
HTML
<form action='{{trustedUrl}}' method="POST" target='iframe'>
<input type="text" />
<input type="submit", value="submit" />
</form>
Java Script
var testCtrl = ['$scope',function($scope){
var pageInitialize = function(){
$scope.trustedUrl = '';
getUrl(function(data){
trustedUrl = data.URL;
});
}
}]
You missed out $scope here
getUrl(function(data){
$scope.trustedUrl = data.URL;
//-----^
});
You are missing $sce as follows:
var testCtrl = ['$scope','$sce',function($scope,$sce){
var pageInitialize = function(){
$scope.trustedUrl = '';
getUrl(function(data){
trustedUrl = $sce.trustAsResourceUrl(data.URL);
});
}
}]
You can read more about $sce in the angular documentation.
This works for me in Angular 2
<form target="frame" action="<Your URL to POST>" #form method="POST" hidden="hidden">
<input name="token" value={{token}}>
</form>
And call nativeElement.submit() from nginint() in your component.
similar here
Angular way to submit form data to iframe

Pass angularJS $index into onchange

I have an input file within a ng-repeat in my angularJS app. I need to pass the $index variable to the onchange attribute. I'm using onchange and not ng-change because I need the uploaded object (see this post)
In the following code I get 'Uncaught ReferenceError: $index is not defined'
Jade code sample:
div.input-group(ng-repeat='filename in filenames track by $index')
input(type='file', onchange="angular.element(this).scope().file_changed(this.files, **$index**)")
In the onchange attribute, the scope is only accessible via angular.element(this).scope(). That's the method you use to call the file_changed() function, and you should use the same in order to have access to the $index attribute:
<input type="file" onchange="angular.element(this).scope().file_changed(this.files, angular.element(this).scope().$index)" />
Notice that this is becoming pretty long! A solution is to simply pass the DOM element to the function, and obtain all the informations from it:
<input type="file" onchange="angular.element(this).scope().file_changed(this)" />
$scope.file_changed = function (element) {
var index = angular.element(element).scope().$index;
var files = element.files;
// …
};

How can I detect keydown or keypress event in angular.js?

I'm trying to get the value of a mobile number textbox to validate its input value using angular.js. I'm a newbie in using angular.js and not so sure how to implement those events and put some javascript to validate or manipulate the form inputs on my html code.
This is my HTML:
<div>
<label for="mobile_number">Mobile Number</label>
<input type="text" id="mobile_number" placeholder="+639178983214" required
ngcontroller="RegisterDataController" ng-keydown="keydown">
</div>
And my controller:
function RegisterDataController($scope, $element) {
console.log('register data controller');
console.log($element);
$scope.keydown = function(keyEvent) {
console.log('keydown -'+keyEvent);
};
}
I'm not sure how to use the keydown event in angular.js, I also searched how to properly use it. And can i validate my inputs on the directives? Or should I use a controller like what I've done to use the events like keydown or keypress?
Update:
ngKeypress, ngKeydown and ngKeyup are now part of AngularJS.
<!-- you can, for example, specify an expression to evaluate -->
<input ng-keypress="count = count + 1" ng-init="count=0">
<!-- or call a controller/directive method and pass $event as parameter.
With access to $event you can now do stuff like
finding which key was pressed -->
<input ng-keypress="changed($event)">
Read more here:
https://docs.angularjs.org/api/ng/directive/ngKeypress
https://docs.angularjs.org/api/ng/directive/ngKeydown
https://docs.angularjs.org/api/ng/directive/ngKeyup
Earlier solutions:
Solution 1: Use ng-change with ng-model
<input type="text" placeholder="+639178983214" ng-model="mobileNumber"
ng-controller="RegisterDataController" ng-change="keydown()">
JS:
function RegisterDataController($scope) {
$scope.keydown = function() {
/* validate $scope.mobileNumber here*/
};
}
Solution 2. Use $watch
<input type="text" placeholder="+639178983214" ng-model="mobileNumber"
ng-controller="RegisterDataController">
JS:
$scope.$watch("mobileNumber", function(newValue, oldValue) {
/* change noticed */
});
You were on the right track with your "ng-keydown" attribute on the input, but you missed a simple step. Just because you put the ng-keydown attribute there, doesn't mean angular knows what to do with it. That's where "directives" come into play. You used the attribute correctly, but you now need to write a directive that will tell angular what to do when it sees that attribute on an html element.
The following is an example of how you would do that. We'll rename the directive from ng-keydown to on-keydown (to avoid breaking the "best practice" found here):
var mod = angular.module('mydirectives');
mod.directive('onKeydown', function() {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
// this next line will convert the string
// function name into an actual function
var functionToCall = scope.$eval(attrs.ngKeydown);
elem.on('keydown', function(e){
// on the keydown event, call my function
// and pass it the keycode of the key
// that was pressed
// ex: if ENTER was pressed, e.which == 13
functionToCall(e.which);
});
}
};
});
The directive simple tells angular that when it sees an HTML attribute called "ng-keydown", it should listen to the element that has that attribute and call whatever function is passed to it. In the html you would have the following:
<input type="text" on-keydown="onKeydown">
And then in your controller (just like you already had), you would add a function to your controller's scope that is called "onKeydown", like so:
$scope.onKeydown = function(keycode){
// do something with the keycode
}
Hopefully that helps either you or someone else who wants to know
You can checkout Angular UI # http://angular-ui.github.io/ui-utils/ which provide details event handle callback function for detecting keydown,keyup,keypress
(also Enter key, backspace key, alter key ,control key)
<textarea ui-keydown="{27:'keydownCallback($event)'}"></textarea>
<textarea ui-keypress="{13:'keypressCallback($event)'}"></textarea>
<textarea ui-keydown="{'enter alt-space':'keypressCallback($event)'}"> </textarea>
<textarea ui-keyup="{'enter':'keypressCallback($event)'}"> </textarea>
JavaScript code using ng-controller:
$scope.checkkey = function (event) {
alert(event.keyCode); //this will show the ASCII value of the key pressed
}
In HTML:
<input type="text" ng-keypress="checkkey($event)" />
You can now place your checks and other conditions using the keyCode method.

html5 form checkValidity() method not found

I am trying to use the form method checkValidity().
http://html5test.com/ tells me that my browser (Chrome) support the form-level checkValidity method.
However, using jsfiddle http://jsfiddle.net/LcgnQ/2/ I have tried the following html and javascript snippets:
<form id="profileform" name="profileform">
<input type="text" id="firstname" required>
<input type="button" id="testbutton" value="Test">
</form>
$('#testbutton').bind('click',function(){
try{
alert($('#profileform').checkValidity());
}
catch(err){alert('err='+err)};
});
I'm getting an error: object has no method checkValidity()
What am I doing wrong?
Try:
$('#profileform')[0].checkValidity()
When you select $('#profileform') you get a jQuery object array. To access actual DOM properties you must select the first item in the array, which is the raw DOM element.
#robertc 's Answer is perfect. Anyway I'd just add another way to do it using jQuery's .get([index]) function. It also retrieves the DOM element for the given index, or all of the matched DOM elements if there's no index declared.
In the end it is exactly the same, only written in a bit more verbose way:
$('#profileform').get(0).checkValidity()
Leaving you the docs right here: https://api.jquery.com/get/
Just another way:
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByName('profileform');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
}, false);
});