How to dynamically change input value - angularjs

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

Extracting only the value out of a json with angularjs

I try to do this:
.js:
app.controller('appControler', function($scope, $http) {
$http.get(apiBaseURL + "getMyName")
.then(function(response) {
$scope.myName = response.data;
});
});
.html:
<div class="form-group">
<input class="form-control" type="text" placeholder={{myName}}
style="width:106%;" input disabled>
</div>
What I receive in the web is this:
{"getMyName":"Test Name"}
What I want is only this:
Test Name
What Im missing here?
You need to use the Dot Operator {{myName.getMyName}}
<input class="form-control" type="text" placeholder={{myName.getMyName}}
style="width:106%;" input disabled>

How to use one controller for multiple inputs with the same logic?

I have the following scenario, one form with multiple inputs and i need to calculate every input the same way but return the values to different fields
<div class="row">
<input type="number" min="1" class="form-control" id="InputValorFOR" placeholder="" ng-change="findModifier()" ng-model="atrb.for">
<p>{{mod.for}}</p>
</div>
<div class="row">
<input type="number" min="1" class="form-control" id="InputValorDES" placeholder="" ng-change="findModifier()" ng-model="atrb.des">
<p>{{mod.des}}</p>
</div>
the controller:
app.controller('atributosCtrl', function($scope){
findModifier = function() {
if ($scope.atrb > 1 && $scope.atrb <10)
{
if ($scope.atrb % 2 == 0)
{
$scope.mod = (($scope.atrb / 2) - 5);
}
}
};
$scope.$watch('atrb', findModifier); });
I want to change the value of mod.for or mod.des without having to write a controller for each input. but i don't how to pass the name of the model from the input that i'm modifying
I don't know what exactly you want, but I made some changes on your code to make it working. Please tell me what you want in comments here and I'll can help you.
Your HTML modified:
<body ng-controller="atributosCtrl">
<div class="row">
<input type="number" min="1" class="form-control" id="InputValorFOR" placeholder="" ng-change="findModifier('for')" ng-model="atrb.for">
<p>{{mod.for}}</p>
</div>
<div class="row">
<input type="number" min="1" class="form-control" id="InputValorDES" placeholder="" ng-change="findModifier('des')" ng-model="atrb.des">
<p>{{mod.des}}</p>
</div>
</body>
Your JS modified:
app.controller('atributosCtrl', function($scope){
$scope.atrb = {
for: null,
des: null
};
$scope.mod = {
for: null,
des: null
};
$scope.findModifier = function(type) {
$scope.mod[type] = null;
if ($scope.atrb[type] > 1 && $scope.atrb[type] <10)
{
if ($scope.atrb[type] % 2 === 0)
{
$scope.mod[type] = (($scope.atrb[type] / 2) - 5);
}
}
}
});
Plunker:
https://plnkr.co/edit/aCNJQyfYXZ5vU1rc381S
I think you are expecting somethin like this. You can write a custom directive with a link function like below
(function () {
"use strict";
angular.module("app").directive("notifypropertychanged", notifypropertychanged);
function notifypropertychanged() {
var directive = {
require: "ngModel",
link: function ($scope, element, attrs, ngModel) {
$scope.$watch(attrs["notifypropertychanged"], function (newVal, oldVal) {
var initialValue = attrs["oldvalue"];
});
}
};
return directive;
}
})();
Apply this directive on your input
<input type="number" min="1" class="form-control" notifypropertychanged="atrb.des" oldvalue=" {{::atrb.des}} " id="InputValorDES" placeholder="" ng-model="atrb.des">
whenever the value change it will hit on custom watch
I hope this helps

Angular directive multiple inputs one model

HTML:
<html ng-app="app">
<div class="container" style="margin-top: 30px">
<input type="text" ng-model="newName" key-filter/>
<input type="text" ng-model="newName" key-filter/>
<input type="text" ng-model="newName" key-filter/>
<input type="text" ng-model="newName" key-filter/>
</div>
</html>
JS:
var app = angular.module('app', []);
app.directive('keyFilter', function() {
var pattern = /([\s !$%^&*()_+|~=`{}\[\]:";'<>?,.\/])/;
function link(scope) {
scope.$watch('model', function() {
if(scope.model === undefined)
return
if(pattern.test(scope.model)) {
scope.model = scope.model.replace(pattern, '');
Materialize.toast('Denied symbol', 4000, 'rounded');
}
});
}
return {
restrict: 'A',
scope: {
model: '=ngModel'
},
link: link
}
});
I have many inputs which are bind to the same model, and I am filtering user input, when user press a denied key I wanted to show a toast to inform him that he can't use this symbol, but the count of toasts is equal to the count of inputs bind to the same model.
I thought i'm working only with model which is one.
Example here:
http://codepen.io/anon/pen/XbLjVY?editors=101
How can I fix that, or change the logic how it works
p.s. angular beginner
If they are all bind to the same model every change in one is send to the others, so just put your directive on one input not all of them.
Here is a working plunkr :
http://plnkr.co/edit/dI5TMHms2wsPHc9Xqewf?p=preview
using :
<input type="text" ng-model="newName" key-filter/>
<input type="text" ng-model="newName" />
<input type="text" ng-model="newName" />
<input type="text" ng-model="newName" />
You can see in the console the message being displayed only once and from any input field

Angular directive for horizontal Bootstrap form

I'm trying to build a directive for my Angular to help with the integration of form fields. I've implemented Scott Allens solution from his Angular playbook, and it works fine for a normal stacked form.
I need however to adapt it to a horizontal form instead. Here's my code:
Markup
<div form-group>
<label for="name">Name</label>
<input type="text" id="name" ng-model="vm.name">
</div>
formGroup directive
function link(scope, element) {
setupDom(element[0]);
}
function setupDom(element) {
var label = element.querySelector("label");
label.classList.add("control-label");
var input = element.querySelector("input, textarea, select");
var type = input.getAttribute("type");
if (type !== "radio" && type !== "checkbox"){
input.classList.add("form-control");
}
element.classList.add("form-group");
}
function formGroup() {
return {
restrict: "A",
link: link
}
}
The output becomes:
<div form-group="" class="form-group">
<label for="name" class="control-label">Name</label>
<input type="text" id="name" ng-model="vm.name" class="form-control">
</div>
And that's fine for stacked form. Since I need a horizontal form, my output needs to look like this:
<div form-group="" class="form-group">
<label for="name" class="control-label col-sm-3">Name</label>
<div class="col-sm-9">
<input type="text" id="name" ng-model="vm.name" class="form-control">
</div>
</div>
I've tried many solutions and I can get it work with single elements like an input, textarea or a select. It becomes much more tricky when I have something like two radio buttons inside my markup like this:
<div form-group>
<label>Active</label>
<div class="radio">
<label>
<input type="radio" name="active" ng-value="true" ng-model="vm.active"> Yes
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="active" ng-value="false" ng-model="vm.active"> No
</label>
</div>
</div>
The desired output of the above mentioned code should be:
<div form-group class="form-group">
<label class="control-label col-sm-3">Active</label>
<div class="col-sm-9">
<div class="radio">
<label>
<input type="radio" name="active" ng-value="true" ng-model="vm.active"> Yes
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="active" ng-value="false" ng-model="vm.active"> No
</label>
</div>
</div>
</div>
Please notice that the input(s) in the form-group is not fixed. It can be either a single input, textarea, select, a group of radio buttons or checkboxes. I'm lost for how I can make that happen. Any help is appreciated. Thanks!
UPDATE
I made some small changes to Mark Veenstra's code to make it (sort of) working:
function setupDom(element) {
element.classList.add("form-group");
var label = element.querySelector("label");
label.classList.add("control-label", "col-sm-3");
var input = element.querySelector("input, textarea, select");
var type = input.getAttribute("type");
if (type !== "radio" && type !== "checkbox"){
input.classList.add("form-control");
angular.element(input).wrap(angular.element('<div class="col-sm-9"></div>'));
}
var div_radio = element.querySelector("div[class='radio']");
angular.element(div_radio).wrap(angular.element('<div class="col-sm-9"></div>'));
}
This does not work completely as intended with multiple radio inputs since it only wraps the <div> on the first radio input element.
The output from radio button example in my original post using Marks code is:
<div form-group="" class="form-group">
<label class="control-label col-sm-3">Active</label>
<div class="col-sm-9">
<div class="radio">
<label>
<input type="radio" name="active" ng-value="true" ng-model="vm.active" value="true"> Yes
</label>
</div>
</div>
<div class="radio">
<label>
<input type="radio" name="active" ng-value="false" ng-model="vm.active" value="false"> No
</label>
</div>
</div>
SOLUTION
Check out the Plunker with the final result: http://plnkr.co/edit/Wv6V86hHTCz3URS9DhdU?p=preview
In the angular.element documentation you can find the method wrap() to be able to wrap HTML around a selected element. Or see this direct link.
So what you could do in your directive is change the setupDom() function to match your requirements per type of form element.
function link(scope, element) {
setupDom(element[0]);
}
function setupDom(element) {
element.classList.add("form-group");
var label = element.querySelector("label");
label.classList.add("control-label col-sm-3");
var input = element.querySelector("input, textarea, select");
var type = input.getAttribute("type");
if (type !== "radio" && type !== "checkbox"){
input.classList.add("form-control");
input.wrap(angular.element('<div class="col-sm-9"></div>'));
}
var div_radio = element.querySelectorAll("div[class='radio']");
div_radio.wrap(angular.element('<div class="col-sm-9"></div>'));
}
function formGroup() {
return {
restrict: "A",
link: link
}
}
NOTE: This code is not tested, maybe there are some minor mistakes, but I guess you'll get the point now.
Mark's suggestion came close, but it didn't solve my problem completely. I ended up using the following code in my formGroup directive:
(function (module) {
"use strict";
function link(scope, element) {
setupDom(element[0]);
}
function setupDom(element) {
element.classList.add("form-group");
var children = angular.element(element).children();
var labels = children.splice(0, 1);
// Set label classes
labels[0].classList.add("control-label", "col-sm-3");
// Wrap children in div
angular.element(children).wrapAll(angular.element("<div class='col-sm-9'></div>"));
// Handle inputs
var inputs = element.querySelectorAll("input, textarea, select");
for (var i = 0, len = inputs.length; i < len; i++) {
var input = inputs[i],
type = input.getAttribute("type");
if (type !== "radio" && type !== "checkbox") {
input.classList.add("form-control");
}
}
}
function formGroup() {
return {
restrict: "A",
link: link
}
}
module.directive("formGroup", formGroup);
}(angular.module("app.core")));
Check out this Plunker to see it in action: http://plnkr.co/edit/Wv6V86hHTCz3URS9DhdU?p=preview

How to get data from ngform in angularjs?

HTML:
<div ng-controller="TestController" >
<form name="test_form" ng-submit="submit()">
<input type="text" name="some_name" ng-model="form_data.some_name" required>
<ng-form ng-repeat="key in keys" name="keyForm">
<input type="text" name="data_input" ng-model="form_data.data_input" required>
</ng-form>
<a ng-click="addKey()">NEW KEY</a>
</form>
</div>
JS:
app.controller('TestController', function TestController($scope){
$scope.keys = [];
$scope.addKey = function() {
$scope.keys.push({});
}
$scope.submit = function() {
console.log($scope);
}
});
In submit function I can get the value of "some_name" input:
$scope.submit = function() {
console.log($scope.form_data.some_name);
}
But I can't get the values of "data_input" inputs (they are inside ngform tag). How to do that?
(ngform tag is using for ability to validate each new added input separately)
Each input inside the ng-repeat needs its own unique ng-model property -- they all can't use form_data.data_input. Here is one way to solve your problem:
<ng-form ng-repeat="key in keys" name="keyForm">
<input type="text" name="data_input" ng-model="key.data" required>
</ng-form>
$scope.addKey = function () {
$scope.keys.push({ data: ''});
}
Fiddle.
See also https://stackoverflow.com/a/14379763/215945

Resources