How to change form input value dynamically in AngularJS [duplicate] - javascript

I'm trying to show some editable results to the users, so I show them through an input field. This is a basic example of what I'm doing:
<div class="form-group">
<label>First number</label>
<input type="text" ng-model="first" ng-required="true" class="form-control">
</div>
<div class="form-group">
<label>Second number</label>
<input type="text" ng-model="second" ng-required="true" class="form-control">
</div>
<div class="form-group">
<label>The sum is: {{first + second }}</label>
<input type="text" ng-model="result" ng-required="true" class="form-control">
</div>
In the result's div, I used a label to test if the result is being obtained correctly, and it is. But if I edit the first or second values, the input's result doesn't update.
This is the controller used (yeah, the form is in a modal):
var ModalInstanceCtrl = function ($scope, $modalInstance) {
$scope.result = $scope.first + $scope.second;
$scope.confirm = function () {
$modalInstance.close(result);
};
$scope.cancelNewBet = function () {
$modalInstance.dismiss('cancel');
};
};
I thought the value was supposed to get automatically updated once I define how it is obtained. But clearly it misses something to change the result through script...
Thanks in advance.

What do you want to happen when the user edits the results input? Do you want the data binding to break (I assume not and ignore this possibility)? Do you want one of the inputs to adjust to the proper value?
If you only want to display the output, do this, in your controller:
$scope.result = function() { return $scope.first + $scope.second; }
And in your view:
{{ result() }}
But if you want the user to be able to edit the result and (let's say) have second be assigned (result - first), then you'd want something like this in your view (by the way, note the type="number"):
<input type="number" ng-change="adjustResult()" ng-model="first">
<input type="number" ng-change="adjustResult()" ng-model="second">
<input type="number" ng-change="adjustInput()" ng-model="result">
And in your controller:
$scope.adjustResult = function() {
$scope.result = $scope.first + $scope.second;
};
$scope.adjustResult(); // initialize result
$scope.adjustInput = function() {
$scope.second = $scope.result - $scope.first;
}

Related

Javascript AngularJs (NG1) If ng-model value is null

I am using AngularJs (Angular1) in a project and I have an ng-model which gets a value:
<input id="myinput" type="text" class="form-control" ng-model="ctrl.myDate" ng-required="true" />
This works fine as far as ctrl.myDate is not null be breaks the code when it's null
Is there a way where I can check if the value is null and add (for example) today's date if it's null, so it doesn't break?
How can I do this?
<input ng-if="ctrl.myDate" id="myinput" type="text" class="form-control" ng-
model="ctrl.myDate" ng-required="true" />
<!-- default date when myDate is null -->
<input ng-if="!ctrl.myDate" id="myinput" type="text" class="form-control" ng-
model="ctrl.defaultDate" ng-required="true" />
You can store a defaultDate in the $scope.ctrl.
1) Supposing that ctrl.myDate is null, then it is probably initialized somewhere in your controller. Based upon that, the right place to replace the model value is your controller and not the view.
So in this case your code might look something like this:
function setDate() {
const today = new Date();
vm.myDate = getDate() || today; // If date is null then assign today.
}
function getDate() { //This might be an http call that brings the date.
return null;
}
2) On the other hand if your model is just for presentation purpose you can do something like this using ng-value directive, but there is probably no reason to use input tag.
<input id="myinput" type="text" class="form-control" ng-value="ctrl.myDate || ctrl.today" ng-required="true" />
Here's a working sample based on your question.
Can you move the condition to where you controller is initialized rather than in the ng-model? e.g. ng-init?
var myApp = angular.module('myApp',[]);
myApp.controller('TestController', ['$scope', function($scope) {
var testController = this;
testController.init = function (dateInput) {
if (dateInput !== null) {
testController.myDate = dateInput !== null ? dateInput : getDate();
}
};
}]);
and
<div ng-controller="TestController as ctrl" ng-init="ctrl.init(yourDate)">
<input id="myinput" type="text" class="form-control" ng-model="ctrl.myDate" ng-required="true" />
</div>

get localstorage value and put in textbox angulars

i have a textbox called item and when the page loads i want to get a value from the localstorage and put it in the textbox item which i later send to the database.
HTML:
<div ng-controller="newitem_ctrl">
<input name="item" type="text" id="item" placeholder="Name of Item" ng-model="item" required="required">
</div>
JS:
.controller('newitem_ctrl', function($scope,$http,$location,$ionicLoading,$ionicPopup, $timeout){
$scope.item = localStorage.getItem("shop_id")
$scope.insertnew = function() {
$ionicLoading.show({template: '<p>Adding...</p><ion-spinner></ion-spinner>'});
event.preventDefault();
$http.post("http://localhost/myweb/insert.php",
{'item':$scope.item,'quantity'})
.success(function(data,status,headers,config){
console.log(data)
{$ionicLoading.hide();}
}).error(function(error){
console.error(error);
});
}
})

Set ng-model value to button click

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

Angularjs keep the focus on a field after ng-click?

I try to figure out how I can keep the focus on an input field in angularjs after I click on a button.
My goal is to prevent my mobile to hide his keyboard right after I click on the + button. I want to keep the focus on input choice.
Like this the user can add a new choice without the need to click again on my input.
<div id="demo" ng-app="Foobar">
<div ng-controller="DemoCtrl">
<input type="text" ng-model="title" placeholder="title" />
<input type="text" ng-model="choice" placeholder="choice" />
<button ng-click="addChoice(choice)">+</button>
{{choices}}
</div>
</div>
angular.module('Foobar', [])
.controller('DemoCtrl', ['$scope', function ($scope) {
$scope.choices = [];
$scope.addChoice = function (choice) {
$scope.choices.push(choice);
};
}]);
http://jsfiddle.net/gbg09bto/
What is the best strategy ? (directive, ng-focus)
simplest thing is do it by plain javascript
to do it
in html // put a id attribute
<input type="text" id="choice" ng-model="choice" placeholder="choice" />
in controller function
$scope.addChoice = function (choice) {
$scope.choices.push(choice);
document.getElementById("choice").focus(); // get the element by id & focus the input
};
here is the updated Fiddle

Knockout foreach bound to value in inputfield

I want to autogenerate a number of labels on the bottom of my page based on what someone fills in in an inputfield.
So when someone fills in "2", I want 2 labels to pop up, preferable when he typed it without leaving the inputfield or anything.
This is what I have:
HTML
<div class="form-group">
<label class="control-label" for="if_aantalMensen">
Hoeveel extra mensen wil je inschrijven?
</label>
<div>
<input type="text" class="form-control" id="if_aantalMensen" name="if_aantalMensen"
data-bind="textInput: aantalMensen">
</div>
</div>
<div data-bind="foreach: aantalMensenArray" class="form-group">
<label><span data-bind="text: $index"></span></label>
</div>
Javascript
var vm = {
aantalMensen: ko.observable(0),
aantalMensenArray: ko.computed(function() {
var fields = [];
for (var i = 0; i < self.selectedNumberOfFields(); i++) {
fields.push(new Parameter());
}
return fields;
})}
It works if I just make "aantalMensenArray" into an observableArray that already has values in it. However, I can't get it to change the amount of labels shown.
Use valueUpdate:'afterkeydown'
"http://jsfiddle.net/dpa6zk9j/"

Categories