Set ng-model value to button click - javascript

I have this little snippet of code to set the root.lowWeight and root.highWeight to my controller.
<input type="number" placeholder="Enter Low Range..." class="form-control input-xs">
<input type="number" placeholder="Enter High Range..." class="form-control input-xs">
<button class="btn btn-primary" ng-click="assignWeights()">Select Model</button>
Controller model:
//set the initial root scope to empty object
$scope.root = {};
//define root weight
$scope.root.lowWeight = 0;
$scope.root.highWeight = 0;
I know I could just use ng-model="root.lowWeight" to set the value, but ng-model triggers on element input event.
How can I either:
a) Send the input values in via assignWeights(param1, param2)
b) Change ng-model to trigger input on button click (seems hacky, less preferred solution)
I also know I could use JS/jQuery to trigger the input event and block the input event, but that's a last ditch effort I will 99.9% not do.

Solution using seperate scope object: plunkr
Html:
Low: <input type="text" name="lowRange" ng-model="inputData.lowWeight">
High: <input type="text" name="highRange" ng-model="inputData.highWeight">
Js:
$scope.assignWeights = function() {
$scope.lowWeight = $scope.inputData.lowWeight;
$scope.highWeight = $scope.inputData.highWeight
}

In your assignWeights function, you could use a selector to retrieve the values of the inputs and then assign your scope variable values based on that. Just assign a name to each input.
E.g.
<input type="number" placeholder="Enter Low Range..." class="form-control input-xs" name="lowRange">
<input type="number" placeholder="Enter High Range..." class="form-control input-xs" name="highRange">
<button class="btn btn-primary" ng-click="assignWeights()">Select Model</button>
Controller:
$scope.assignWeights = function() {
$scope.root.lowWeight = document.querySelector('input[name="lowRange"]').value
$scope.root.highWeight = document.querySelect('input[name="highRange"]').value
}
Plunker: http://plnkr.co/edit/lm8GFA0CD0zWwgAMSLah?p=preview

Related

Not able to find the value of a textbox from DOM

I have the below input tag for a textbox. The value is getting displayed in
UI but I am not able to retrieve it from DOM. Any suggestions how we can extract the value from the below tag
<input id="f_aDE8F92F6A8E345D19EB6A819D317DFA89AF_3_1"
class="x-form-text x-form-field dct-field x_normalBG x-form-focus"
size="14"
autocomplete="off"
fieldref="ClientConsiderationsAL.LinesOfInsuranceOfTheClientWithABC"
objectref="aDE8F92F6A8E345D19EB6A819D317DFA8" maxlength="14"
name="int_9AF" title="" type="text"/>
If you're using angularjs add ng-model="relevant-name" to the input and in the controller add $scope.relevant-name as a variable to bind to like this: https://www.w3schools.com/angular/angular_model.asp
If it's just javascript then you need to do something like this:
https://plnkr.co/edit/wU13Bnd6j3TRfYcNV9ZG?p=preview
<input id="f_aDE8F92F6A8E345D19EB6A819D317DFA89AF_3_1"
class="x-form-text x-form-field dct-field x_normalBG x-form-focus"
size="14"
autocomplete="off"
fieldref="ClientConsiderationsAL.LinesOfInsuranceOfTheClientWithABC"
objectref="aDE8F92F6A8E345D19EB6A819D317DFA8" maxlength="14"
name="int_9AF" title="" type="text" onkeyup="textChanged()"/>
<script>
function textChanged() {
var input =
document.getElementById('f_aDE8F92F6A8E345D19EB6A819D317DFA89AF_3_1');
console.log(input.value);
}
</script>

Getting another element through a method thats related to the current operation

Sorry for the bad title, simple couldn't figure out how to explain my problem.
Let's say i have 4 of these fields, and not just one. I want to increment or decrement each input field. Each input field has a "+" and "-" that does incremental and decremental tasks.
I have setup a method that register the v-on click even to a method. But how do i get what input field it was incremented on, cause 'this' would return the buttons of +/-
normally i would just use jquery with .parent().find('.input-number'); but i feel like this is dirty, and excessive for such a small thing. most be a better approach?
This is my markup
<div class="form-group">
<span class="input-number-decrement" v-on:click="decrement()">–</span>
<input class="input-number form-control" name="pack1" id="pack1" type="text" value="0" min="0">
<span class="input-number-increment" v-on:click="increment()">+</span>
</div>
and looks like this
example of the field
any help would great, since i'm stuck at this part :)
I have created one javascript function for increment and decrement value by 1.
HTML
<div class="form-group">
<span class="input-number-decrement" v-on:click="inc_dec('dec')">-</span>
<input class="input-number form-control" name="pack1" id="pack1" type="text" value="0" min="0">
<span class="input-number-increment" v-on:click="inc_dec('inc')">+</span>
</div>
Javascript
<script type="text/javascript">
function inc_dec(flag){
var pack1 = document.getElementById('pack1');
var inc_dec_by = 1;
if(flag=='inc'){
pack1.value = parseInt(pack1.value)+inc_dec_by;
}
if(flag=='dec'){
pack1.value = parseInt(pack1.value)-inc_dec_by;
}
}
</script>
I am assuming above code is a vue component.
<div class="form-group">
<span class="input-number-decrement" v-on:click="decrement()">–</span>
<inputn v-model="value" class="input-number form-control" name="pack1" id="pack1" type="text" value="0" min="0">
<span class="input-number-increment" v-on:click="increment()">+</span>
</div>
In the script define a variable to hold the value.Then manipulate values using defined methods
<script>
export default{
data: {
value
},
methods: {
decrement: function (event) {
},
increment: function (event) {
}
}
}
</script>

AngularJS: ng-model not clearing input

I have a dynamic input for CPFs (Brazilian 'social security' number).
Every time I enter one CPF, another input should be displayed, and so on..
But for some reason, the ng-model is not being cleared after the CPF is added.
Here's my HTML (inside a directive with isolate scope):
<div ng-repeat="cpf in cpfs" class="field-input">
<input type="text" class="field" ng-model="cpf.number" required>
<label>added CPF</label>
</div>
<div class="field-input">
<input type="text" class="field" ng-model="cpf.number" required>
<label>add new CPF</label>
<button ng-click="addCpf(cpf)" class="btn btn-primary">add</button>
</div>
Here's my controller (inside a directive with isolate scope):
$scope.cpfs = [];
$scope.addCpf = function(cpf) {
$scope.cpfs.push(angular.copy(cpf));
delete $scope.cpf;
};
instead of delete $scope.cpf; use $scope.cpf.number = "";
we can't delete an model, we have to set it to blank, because its linked with our View part

ng-pattern not functioning in AngularJS

<label for="updateInterval" class="control-label" for="UpdateInterval">Select Interval</label>
<input name="intervalRange" id="intervalRange" ng-pattern="" type="number" class="form-control input-medium fld-updateinterval-val" placeholder="" ng-model="update_interval" ng-required="true" >
<select class="form-control input-medium sampleForm-combo" onchange="changetextbox(this.value)" id="action" ng-model="update_intervalSelect" ng-required="true">
<option></option>
<option value="days">days</option>
<option value="hours">hours</option>
</select>
Above I have an input box and a dropdown list where the value being inputted in the first text box depends on the value being chosen in at the dropdown list. The JavaScript is reading it well, but my problem is that ng-pattern is not functioning, and I don't know why. If I check it in Firebug, it is being shown that ng-pattern is placed into the textbox, but I'm not sure why I am still able to input numbers that are not within the range I have specified.
function changetextbox(interval)
{
if(interval == "days"){
$(".fld-updateinterval-val").attr("placeholder", "1-365");
$(".fld-updateinterval-val").attr("ng-pattern", "/\\b([1-9][0-9]?|[12][0-9]{2}|3[0-5][0-9]|36[0-5])\\b/");
}
else if (interval == "hours"){
$(".fld-updateinterval-val").attr("placeholder", "1-8760");
$(".fld-updateinterval-val").attr("ng-pattern", "/\\b([1-9][0-9]{0,2}|[1-7][0-9]{3}|8[0-6][0-9]{2}|87[0-5][0-9]|8760)\\b/");
}
Just adding ng-pattern as an attribute to input tag or changing it like above wont work. It requires to compile the element by $compile service in order to work properly.
Another simple way of achieving above thing is bind with some scope variable.
angular.module('textInputExample', [])
.controller('ExampleController', ['$scope',
function($scope) {
$scope.example = {
text: 'guest',
word: /[a-z]/,
changengpattern: function() {
this.word = /[0-9]/;
}
};
}
]);
HTML
<form name="myForm" ng-controller="ExampleController">
Single word:
<input type="text" name="input" ng-model="example.text" ng-pattern="example.word" required ng-trim="false">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.pattern">
Single word only!</span>
<tt>text = {{example.text}}</tt>
<br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt>
<br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt>
<br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt>
<br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt>
<br/>
<input type="button" value="click me to change ng pattern" ng-click="example.changengpattern()" />
</form>
Here is working fiddle for you
I had the same issues until I found out, that angular needs both starting and string-end tag within your regex.
Your examples then would look like:
$(".fld-updateinterval-val").attr("ng-pattern", "/^\\b([1-9][0-9]?|[12][0-9]{2}|3[0-5][0-9]|36[0-5])\\b$/");
$(".fld-updateinterval-val").attr("ng-pattern", "/^\\b([1-9][0-9]{0,2}|[1-7][0-9]{3}|8[0-6][0-9]{2}|87[0-5][0-9]|8760)\\b$/");
Pay attention to the pattern string starting with /^ and finishing up with $/. This solved my issues with custom ng-patterns.
ng-pattern= "/^([0-9][0-9]{0,2}|[1-7][0-9]{3}|8[0-6][0-9]{2}|87[0-5][0-9]\d|8760)$/"
provide the regex ("/\\b([1-9][0-9]?|[12][0-9]{2}|3[0-5][0-9]|36[0-5])\\b/") into the input where inside the ng-pattern.
For example,
ng-pattern="/\\b([1-9][0-9]?|[12][0-9]{2}|3[0-5][0-9]|36[0-5])\\b/"
It Worked for me....

Cannot get model value in Controller method in Angular js

I am developing an app in Angular js
javascript:
$scope.spentAmount = function() {
angular.forEach($scope.expenses, function(expense) {
if(expense.done){
console.log($scope.spentamount);
}
});
//return amount;
};
HTML:
<label for="spentby">Spent by</label>
<ul class="unstyled">
<li ng-repeat="expense in expenses">
<input type="checkbox" ng-model="expense.done">
<span>{{expense.text}}</span>
<input type="text" ng-show="expense.done" ng-model="spentamount" size="30"
placeholder="Enter the amount">
</li>
</ul>
<form ng-submit="addExpense()">
<input type="text" ng-model="expenseText" size="30"
placeholder="Enter the names">
<input class="btn-primary" type="submit" value="Add">
</form>
<label for="amountspent">Amount spent(Rs)</label>
<span>{{spentAmount()}}</span><br>
but console.log($scope.spentamount) returns undefined.
But the method gets called
Please Advice
The reason for the 'undefined' is in the async behaviour. Your code is going through the collection of expenses sooner then it is loaded. Check the $watch(watchExpression, listener, objectEquality)
a draft how to observe changing colleciton expenses
// a new variable containing total
$scope.total = 0;
$scope.$watch('expenses', function (exps) {
angular.forEach(exps, function (exp) {
if(exp.done){
// here should/must be your calculation
$scope.total + exp.Amount;
}
});
});
now we can adjust the template and consume the up-to-date result
<!--<span>{{spentAmount()}}</span><br>-->
<span>{{total}}</span><br>
Also think about introducing something like $scope.myModel = { expenses : [], total : 0 }... Because:
if you use ng-model there has to be a dot somewhere. If you don't have a dot, you're doing it wrong...
While binding inside the ng-repeat you need to use $parent to use parent scope, like-
<li ng-repeat="expense in expenses">
<input type="checkbox" ng-model="expense.done">
<span>{{expense.text}}</span>
<input type="text" ng-show="expense.done" ng-model="$parent.spentamount" size="30"
placeholder="Enter the amount" />
</li>

Categories