How can I access field in ng-repeat in a dynamic way? - javascript

I need to elaborate some functions in a ng-repeat, but i can't access the right field with the $watch function.
This is my code but prolly I access the field in a wrong way that cause me Javascript error of undefined.
.html
<body ng-controller="MainCtrl">
<div ng-form="mainForm">
<a ng-click="addNewr1()">Add New r1</a>
<ul>
<li ng-repeat="rb_r1 in currForm.r1" ng-form="subFormr1">
<input type="number" step="0.1" ng-model="rb_r1.runo" name="r_runo" required />
<input type="number" step="0.1" ng-model="rb_r1.rdue" name="r_rdue" required />
<input type="number" step="0.1" ng-model="rb_r1.rsomma"/>
</li>
</ul>
</div>
</body>
.js
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function ($scope) {
$scope.master = {};
$scope.currForm.r1 = [];
$scope.addNewr1 = function (){
$scope.currForm.r1.push({ runo: 0,rdue: 0,rsomma: 0 });};
$scope.$watch('rb_r1.runo + rb_r1.rdue', function (value) {
$scope.rb_r1.rsomma= value;
}, true);
});
So I found a fiddle and modifying it I get the solution, but in a limited way, cause I had to access to the field in a static way. How can i do that in a dinamic way?
http://jsfiddle.net/fe9ws/
TY All!

I am still not clear on what you attempted to do but you do not need a $watch for the task described:
Since "somma" is a calculated You can define your field like this and it will produce the desire result:
<input type="number" name="somma" value="{{social.uno + social.due}}">

I resolved with a for in the $watch function..
$scope.$watch('formData.socials',
function(value){
var i;
for(i = 0; i < value.length; i++)
value[i].somma = value[i].uno + value[i].due;
}, true);
see the fiddle! Ty all
http://jsfiddle.net/JWTE2/

Related

For ng-keyup unable to do event.preventDefault() and ng-keypress lagging behind a value for input type number in angular.js

Problem: Input type number with min, max is not working while typing in input box we can type less/more than min, max value. (but by the arrow of input type number it is working fine.)
Requirement: restrict to enter the value in input type number that not in range of min and max
"Using Angular.js want to solve this problem without an extra directive and without changing the input type number to text."
Plunker
ng-keyup: unable to do event.preventDefault() why? This is why we can type more/less than min or max value.
I am getting the correct value while changing.
ng-keypress: lagging behind 1 value. So the first value is undefined (this is a problem for my question).
I am able to to do event.preventDefault();
Shold be: ng-keyup with event.preventDefault(); or ng-keypress with correct order
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $timeout) {
$scope.myScore;
$scope.limit = function(event, myScore){
console.log(event, $scope.myScore, myScore);
// do your code here myScore should be between (min-max)
event.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<!-- <input type="number" ng-model="myScore" min="0" max="200" ng-keypress="limit($event, myScore)"> -->
<input type="number" ng-model="myScore" min="0" max="200" ng-keyup="limit($event, myScore)">
{{myScore}}
</div>
Try using a previous value to fall back to. Then, since $scope.myScore will be undefined whenever it is given a value that falls outside of what's permitted by your input, check for that in your IF.
HIH
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.limit = function(e) {
console.log( $scope.prevScore,$scope.myScore)
if ($scope.myScore === undefined){
$scope.myScore = $scope.prevScore
}
$scope.prevScore = $scope.myScore;
}
$scope.forInitialValue = function(e) {
if ($scope.myScore === undefined){
$scope.myScore = ""
}
$scope.prevScore = $scope.myScore;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<input type="number" ng-model="myScore" min="0" max="200" ng-change="limit($event)" ng-keydown="forInitialValue($event)"> {{myScore}}
</div>

Array in Angular scope variable has only one member

I am a beginner to AngularJS and thanks to the Angular community on Stackoverflow which is willing to help a newbie like me, I am learning it very well thanks a lot for that.
Today I would like to add a feature to the exercise I was doing yesterday (which can be found here). I would like to keep a record of the pairs of numbers that the user has typed in and show it as a list of lines. To do that, I introduce an array of number objects. Pressing the button adds the current pair to the array.
Currently, it seems like the array contains only member whatever I do to push new members to it. Can anyone help me find my mistake?
var saApp = angular.module("saApp", []);
saApp.controller('numberController', function($scope) {
$scope.numbers = [];
$scope.number = {
number1: 0,
number2: 0,
sumIt: function() {
var numberObject;
numberObject = $scope.number;
return parseInt(numberObject.number1) + parseInt(numberObject.number2);
}
};
$scope.pushIt = function() {
if ($scope.number !== undefined)
$scope.numbers.push($scope.number);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="saApp" ng-controller="numberController">
<input type="text" ng-model="number.number1" placeholder="Enter a number here">
<input type="text" ng-model="number.number2" placeholder="Enter another number here">
<br />{{number.number1}} + {{number.number2}} = {{number.sumIt()}}
<br />
<br />
<button ng-click="pushIt()">Push</button>
<div ng-repeat="number in numbers">
{{number.number1}} + {{number.number2}} = {{number.sumIt()}}
<br />
</div>
</div>
One change in your current code just clone the $scope.number before pushing into the $scope.numbers array.
$scope. pushIt = function() {
if ($scope.number !== undefined)
$scope.numbers.push(angular.copy($scope.number));
}
Why we should clone before pushing.
The $scope.number object is the same always thus all of the elements in the array will have the same $$hashkey and you will get this error
So you should clone or copy the object before pushing, so that the array has new element objects in it.
Working code here
Use object having keys as input fields to be pushed in ng-repeat. Every repeated object will have his own scope and will update biding values accordingly.
Try this:
var saApp = angular.module("saApp", []);
saApp.controller('numberController', function($scope) {
$scope.numbers = [];
$scope.pushIt = function() {
var obj = {
number1: 0,
number2: 0,
sumIt: function() {
return parseInt(this.number1) + parseInt(this.number2);
}
}
$scope.numbers.push(obj);
}
$scope.pushIt();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="saApp" ng-controller="numberController">
<button ng-click="pushIt()">Push</button>
<div ng-repeat="number in numbers">
<input type="text" ng-model="number.number1" placeholder="Enter a number here">
<input type="text" ng-model="number.number2" placeholder="Enter another number here">{{number.number1}} + {{number.number2}} = {{number.sumIt()}}
<br />
</div>
</div>
Fiddle here
$scope.pushIt = function() {
if ($scope.number)
$scope.numbers.push($scope.number);
}
Replace your pushIt function by this Code

Get value from getElementById in angular js

View
<button class="ion-ios-close-outline" ng-click="change()"></button>
<label class="item item-input">
<input id='test' type="text" ng-value="77"/>
</label>
Controller
$scope.change = function () {
var x=angular.element(document.getElementById("test"));
alert(x.value);
};
The output is undefined.
What am i doing wrong in here?
Please help.
angular.element returns wrapper of jQlite. It's similar to jquery. So it doesn't support value.
Either use
x.val()
or
x[0].value
Either way i would recommend not to use such type of changes in controller. It should be done only in directives.
You should use model of input box to access such values in controllers.
Use ng-model on your input;
set ng-model='test'
<input id='test' type="text" ng-model='test' ng-value="77"/>
and on the change function set
var x=$scope.test;
alert(x);
Edited
var a = angular.element(document.getElementById('t'));
var attr = a[0].attributes;
var value = attr.getNamedItem("ng-value");
console.log(value.value);
In my opinion your solution is bad.
Angular API allow to use data binding.
So you should use ng-model in you input compoment for example:
<button class="ion-ios-close-outline" ng-click="change()"></button>
<label class="item item-input">
<input id='test' type="text" ng-model="test"/>
$scope.test = 77;
$scope.change = function () {
alert($scope.test);
};

Angular: How to get an input value using $this

I am hoping to get an input value inside a keyup function that can runs from multiple inputs. Every time there is a keyup the function will trigger according to the specific input. So, I am trying to use $this inside the function. No succes so far..
HTML code:
<input ng-keyup="getRxcui()" placeholder="Type med a" id="medicineA" />
<input ng-keyup="getRxcui()" placeholder="Type med b" id="medicineB" />
Angular code:
var rxConflicts = angular.module('rxConflicts', []);
rxConflicts.controller('MainController', function($scope, $http){
$scope.getRxcui = function(event){
// getting the value for each medicine input
var medValue = $(this).value;
console.log(medValue);
}
});
I am pretty sure $(this) is the right way to do this so that I don't need to duplicate that function for each input and use ng-model... You can take my word that the angular works fine.
Any help is appreciated. Thanks
use ng-model and pass it in function:
<input ng-keyup="getRxcui(medicineA)" ng-model="medicineA" placeholder="Type med a" id="medicineA" />
<input ng-keyup="getRxcui(medicineB)" ng-model="medicineB" placeholder="Type med b" id="medicineB" />
Angular code:
var rxConflicts = angular.module('rxConflicts', []);
rxConflicts.controller('MainController', function($scope, $http){
$scope.getRxcui = function(value){
// getting the value for each medicine input
var medValue = value;
console.log(medValue);
}
});
Angular 2 and superior:
You could pass the $event on the keyUp and use it to get the target (the input) and it's value. In case you're using formControls and not binding directly through ngModel
Template HTML:
<input (keyup)="getRxcui($event)">
Component.ts
getRxcui(event){
var inputValue = event.target.value;
console.log(inputValue);
}

Angularjs ng-required call function

It is possible make the required value dependet of some funcion?
Something like this? I want to do this because I want to change the required attribute to some form inputs...
HTML:
Name: <input type="text" ng-model="user.name" ng-required="isRequired('name')" />
Age: <input type="text" ng-model="user.age" ng-required="isRequired('age')" />
JS:
$scope.isRequired(fieldName){
$scope.requiredFields = [];
//$scope.requiredFields = STUFF FROM SOME REST SERVICE
for (i in requiredFields) {
if (requiredFields[i] == fieldName){
return true;
}
}
return false;
}
Updated Answer:
So based on your updated OP, what you want is certainly doable. The problem with what you were trying to do is that ng-required has no ability to execute a function, it only reads a boolean. But we can dynamically create variables based on data from the server to automatically set fields to required:
Updated Plunker
<form>
Name: <input type="text" ng-model="user.test" ng-required="name" /><br/>
<input type="text" ng-model="user.name" ng-required="age" />
<br/>
<button type="submit">Submit</button>
</form>
Note that I put a $scope property for each input in the ng-required attribute. Now we can dynamically create that $scope property and set it to true if our data says we need to:
$scope.isRequired = function(){
$scope.requiredFields = [];
$http.get('fields.json')
.success(function(data){
$scope.requiredFields = angular.fromJson(data);
console.log($scope.requiredFields.required)
for (i = 0; i < $scope.requiredFields.required.length; i++) {
$scope[$scope.requiredFields.required[i]] = true
}
console.log($scope[$scope.requiredFields.required[0]]);
})
//$scope.requiredFields = STUFF FROM SOME REST SERVICE
}
$scope.isRequired()
So it is iterating over an array of required fields received from the server, and then dynamically creating a $scope property for each one that is required, and setting it to true. Any field that has that $scope property in it's ng-required will be required now. Anything not dynamically created will just return false, and ng-required doesn't trigger.
Original answer:
Plunker
As Pratik mentioned, ng-required only accepts a Boolean value, but we can toggle the value of that with a function.
HTML
<form>
Name: <input type="text" ng-model="user.name" ng-required="isRequired" />
<br/><button ng-click="toggle()">Required: {{isRequired}}</button>
<button type="submit">Submit</button>
</form>
code:
$scope.isRequired = true;
$scope.toggle = function() {
$scope.isRequired = !$scope.isRequired;
}
I know this is a couple of years old and so AngularJS may have changed, but the accepted answer as it stands today isn't correct. You can very easily execute a function within ng-required, as it takes an expression, which can be a function. For example:
index.html
<div ng-controller="ExampleController" class="expressions">
Expression:
<input type='text' ng-model="expr" size="80"/>
<button ng-click="addExp(expr)">Evaluate</button>
<ul>
<li ng-repeat="expr in exprs track by $index">
[ X ]
<code>{{expr}}</code> => <span ng-bind="$parent.$eval(expr)"></span>
</li>
</ul>
</div>
script.js
angular.module('expressionExample', [])
.controller('ExampleController', ['$scope', function($scope) {
var exprs = $scope.exprs = [];
$scope.expr = '3*10|currency';
$scope.addExp = function(expr) {
exprs.push(expr);
};
$scope.removeExp = function(index) {
exprs.splice(index, 1);
};
}]);
In script.js, a function addExp is defined and added to the scope, and then it's called in the ng-click directive of the a tag, which also takes an expression as its argument.
This code is taken directly from the AngularJS documentation on expressions. It doesn't use ng-require directly, but any directive that takes an expression will work the same. I have used the same syntax to use a function for ng-require.

Categories