Storing value of a text input in AngularJS - javascript

I have an input:
In the controller I want to obtain the value of the text input by setting available. For example:
vm.inputValue = document.getElementById('link').value;
It breaks my code as I get a console error of:
TypeError: Cannot read property 'value' of null
What am I doing wrong?

AngularJS have a directive that does it to you, the ng-model. It binds in a variable the input you enter in the HTML and it reflect the changes you make in the variable inside your controller in JavaScript.
In your HTML
<input type="text" ng-model="vm.myText">
{{ vm.myText }} <!-- This is output the value of vm.myText in the HTML -->
<button ng-click="vm.logData()"></button>
In your JavaScript
function MyController(){
var vm = this;
vm.myText = '';
vm.logData = logData;
function logData(){
console.log('Your data is ', vm.myText);
// This easy, you can access your value in the JavaScript
}
}

Probably you forget to set the id (id = "link")of the input field in HTML:
<input id = "link" type = "text">
Also, you can do the same thing using ng-model
<input ng-model = "vm.inputValue" type = "text">
And from controller, you can get the correct value if you define a scope variable:
$scope.vm = {};
$scope.vm.inputValue = "";

Related

Changing ng-class of current element in execution

I have a form which gets generated at runtime. I'm trying to update the class of the input box if validation fails. I'm performing validation on ng-blur = "chaeckValidation()" Now if I'm using ng-class = "active" and set the variable in controller for $scope.active = "has-error-class".
What this is doing is updating class of all the elements in form to error-class css but I want to attach error-class css only to the element which failed validation.
I tried but couldn't find any success. I can't hardcode anything in form as the form is completely dynamic and moreover I'm performing validation through regular expression in function and want to display error message based on which regular expression failed.
Code:
prop.json
[
{ label : Application Name
cid : uniqueId
typeApex : CURRENCY
fieldPath : application_Name__c
type : NUMBER
value : ''
dbRequired : true
isRequired : false
},
{...similar array of JSON object ...},
{}
]
view.html
<div ng-if="prop.type != 'picklist' && prop.type != 'reference'">
<label for="{{prop.label}}">{{prop.label}}</label>
<input type="{{prop.type}}" id="inputFields{{prop.fieldPath}}" ng-blur="fieldValidation(prop.fieldPath, prop.typeApex, $event)" ng-model-options="{updateOn: 'blur'}"
class="form-control" name="{{prop.fieldPath}}" ng-model="fieldPathValue[prop.fieldPath]"
ng-required="isRequired({{prop.dbRequired}}, {{prop.required}})" ng-class ="active"/>
</div>
Controller
$scope.fieldValidation = function(fieldPath, type, $event) {
console.log('fieldPath in fieldValidation ',fieldPath);
var myMap = new Map();
myMap.set("Term__c","^[0-9]+$");
myMap.set("Loan_Amount__c","[0-9]+(\.[0-9][0-9]?)?");
//console.log("fieldPathValue ",$.parseJSON(JSON.stringify($scope.fieldPathValue)));
//console.log("fieldPathValue ",$scope.fieldPathValue);
var value = $event.target.value;
console.log("value ",value);
var reg = new RegExp(myMap.get(fieldPath));
console.log("regex test result ",reg.test(value));
console.log("event ",$event);
if(!reg.test(value)) {
//add error message classs to selected field
//display error message on top of field
$timeout(function(){
$scope.$apply(function () {
$scope.active = "has-error";
});
}, 0);
}
Result Image:
I have made an error in first input field which accepts float numbers and I have provided alphabets, so it throws error but that error is propogated to entire form and not only to the element which triggers it.
How can I make sure only element that fails validation on ng-blur gets the error-class-css attached.
I have tried doing this using getElementById but no success. Added the questions link below.
I have described more on my questions form element in one of my questions. DOM elements not getting updated from angular controller

angular controller only picks up the input values changed

I've got a fairly simple angular controller method :
$scope.addComment = function () {
if ($scope.newComment.message) {
$scope.can_add_comments = false;
new Comments({ comment: $scope.newComment }).$save(function (comment) {
$scope.comments.unshift(comment);
return $scope.can_add_comments = true;
});
return $scope.newComment = {};
}
};
And in my form I have a textarea that holds the value of comment :
<textarea class="required" cols="40" id="new_comment_message" maxlength="2500" ng-disabled="!can_add_comments" ng-model="newComment.message" required="required" rows="20"></textarea>
Works great so far, however I do want to send some data, hidden data with the comment as well. So I added something to hold that value :
<input id="hash_id" name="hash_id" ng-init="__1515604539_122642" ng-model="newComment.hash_id" type="hidden" value="__1515604539_122642">
However when I inspect the $scope.newComment it always comes back as an object with only message as it's property, which is the value from the text area, and I don't get the property on the object hash_id.
When I make this input non hidden and I manually type in the value into the input field and submit a form, I do get a object with hash_id property. What am I doing wrong here, not setting it right?
As far as I know, ng-model doesn't use the value property as a "default" (i.e. it won't copy it back into your model). If you want a default, it should be placed wherever the model is defined:
$scope.newComment = { hash_id: "__1515604539_122642", /* Other params */ };
Alternatively, changing the ng-init to an assignment should work (though I would recommend the above solution instead):
<input id="hash_id" name="hash_id" ng-init="newComment.hash_id = '__1515604539_122642'" ng-model="newComment.hash_id" type="hidden">

Get custom HTML attribute value from controller

I have added a custom attribute (cust-property) to a HTML input control,
<input name="myInputName" type="text" ng-model="myModel" cust-property="My Value">
Now I'm trying to get the value of the custom defined attribute from the validation error object list
for (var i in $scope.form.$error.required) {
var elementName = $scope.form.$error.required[i].$name;
//var customPropertyValue = $scope.form.$error.required[i].cust-property;
}
How can I get the custom HTML attribute value from controller?
Try this:
var id = $scope.form.$error.required[i].attributes['cust-property'].value;
But you should also get a try on directive.
Maybe something like this?
HTML:
<input id="myInputName" name="myInputName" type="text" ng-model="myModel" cust-property="My Value" onClick="getCustom()">
JS:
function getCustom() {
var mydiv = document.getElementById('myInputName');
var custom = mydiv.getAttribute("cust-property");
alert(custom);
}

Failed to get this value in angular js

while Am trying to get current element value in angular controller it throwing error as
Cannot read property 'toLowerCase' of undefined
at m.fn.extend.val (jquery.min.js:4:8638)
at h.promise.then.$scope.validatev (product.js:471:43)
var productApp = angular.module('productApp', ['ngRoute','ngProgress']);
Javascript
productApp.controller('AddOrderController',
function($scope,$http) {
$scope.validatev = function (dis,v)
{
console.log(angular.element(dis).val()); //this line throwing error as above mentioned
}
});
HTML
<input type="text" ng-blur="validatev(this,'req:true');" class="form-control"/>
i can't get the value by ng-model / name property as those are dynamic element in my code , so i'm trying to get that element value by this keyword. please help me to get the this value in controller
Why are you not using the ng-model on your input ?
<input type="text" ng-model="modelRef.thingToValidate" ng-blur="validatev(modelRef);" class="form-control"/>
Then In your JS you have a reference to the input value..
$scope.validatev = function (modelRef)
{
console.log(modelRef.thingToValidate);
};
Note I havent tested this but it just demonstrates the ng-model useage..
Example : Angular Form Documentation
You can use the $event object :
Javascript
productApp.controller('AddOrderController',
function($scope) {
$scope.validatev = function (event, v) {
console.log(event.currentTarget, v);
}
});
HTML
<input type="text" ng-blur="validatev($event,'req:true');" class="form-control"/>

How to return a variable from a javascript function into html body

I am still new to javascript, and I am trying to get a function to return a variable using html & javascript. Basically the function should just return whichever radio button that the user clicks on, although at the moment I don't see anything being returned at all.
The function is here:
<script type="text/javascript">
function GetSelectedItem() {
var chosen = ""
len = document.f1.r1.length
for (i = 0; i <len; i++) {
if (document.f1.r1[i].checked) {
chosen = document.f1.r1[i].value
}
}
}
return chosen
</script>
And then in the html section I have these radio buttons, and my attempt to get the variable "chosen" output to the screen.
<form name = f1><Input type = radio Name = r1 Value = "ON" onClick=GetSelectedItem()>On
<Input type = radio Name = r1 Value = "OFF" onClick =GetSelectedItem()>Off</form>
<script type ="text/javascript">document.write(chosen)</script>
At the moment nothing seems to be getting returned from the function (although if I output the variable 'chosen' inside the function then it is working correctly.
Thanks in advance!
Here's a little simpler approach.
First, make a few corrections to your HTML, and create a container to display the output:
<form name = "f1"> <!-- the "this" in GetSelectedItem(this) is the input -->
<input type = "radio" Name = "r1" Value = "ON" onClick="GetSelectedItem(this)">On
<input type = "radio" Name = "r1" Value = "OFF" onClick ="GetSelectedItem(this)">Off
</form>
<div id="output"></div>
Then change your script to this:
<script type="text/javascript">
// Grab the output eleent
var output = document.getElementById('output');
// "el" is the parameter that references the "this" argument that was passed
function GetSelectedItem(el) {
output.innerHTML = el.value; // set its content to the value of the "el"
}
</script>
...and place it just inside the closing </body> tag.
Click here to test a working example. (jsFiddle)
document.write takes a string, and outputs it as part of the HTML. This is not a live value that updates when the variable pointing at the string is updated.
For that, you will need to perform DOM manipulation.
Change your JavaScript function to something like that:
<script type="text/javascript">
function GetSelectedItem() {
len = document.f1.r1.length;
for (i = 0; i <len; i++) {
if (document.f1.r1[i].checked) {
document.getElementById('test').textContent = document.f1.r1[i].value;
}
}
}
</script>
And then in the body:
<div id="test"></div>
As I put in the post. Using JQuery would make your life easy for this kind of task (and many others for the matter). The really nice thing about JQuery is that it often makes your JavaScript syntax much easier then you can learn the nitty gritty details of javascript as you go.
First, add the following script tag into your html page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
Now you have the JQuery API
Then you could rewrite the function like this.
function GetSelectedItem(btnRadio)
{
var jqElem = $(btnRadio);
$('#output').html(jqElem.attr('value')); //attr('<name of attributre'>) gets the value of the selected attribute
}
Your html would look like this
<form name = "f1">
<input type = "radio" name = "r1" value = "On" onclick="GetSelectedItem(this)">On
<input type = "radio" name = "r1" value = "Off" onclick ="GetSelectedItem(this)">Off
</form>
<div id="output">
</div>
More or less, the .html() can both get and set the html of the selected element. So we are just simply inserting the value into the div tag.

Categories

Resources