Angular JS collect all input values from a div - javascript

I am new to Angular JS, I created a div with input elements and I didn't use ng-model for input boxes.
<div class="row">
<br>
<div class="col-sm-10" id="rankingForm" >
<p ng-repeat=" x in $ctrl.outputProductAttributeValueList">
{{x}} <input type="text" />
</p>
<br>
<button type="submit" ng-click="$ctrl.onRankingFormSubmit()"> SUBMIT</button>
</div>
</div>
When I click on submit button I have to access all input values .Please help me how to do that .. I tried as below.
angular.module("productList")
.component("productList",{
templateUrl : "product-list/product-list.template.html",
controller : ["$http" ,"$scope","$document",function productListController($http,$scope,$document){
var self = this;
self.outputProductAttributeValueList =[ "age", "gender","all"];
self.onRankingFormSubmit = function () {
var queryResult = $document[0].getElementById("rankingForm")
console.log(queryResult);
// HERE queryResult is printing how to proceed further
};
}]
});
Now I want to collect all those input values dynamically created by ng-repeat. Please tell me how to do that ?

AngularJS ngModel is the standard approach for binding the view into the model instead of interacting directly with the DOM.
You can get all the inputs within the div id="rankingForm" you can do:
var inputs = $document[0]
.getElementById('rankingForm')
.getElementsByTagName('input');
Or by using Document.querySelectorAll():
var inputs = $document[0].querySelectorAll('#rankingForm input');
Once you have the inputs than iterate over all of them to get the values.. Notice that I have added attribute name to the inputs:
Code whitout ngModel:
angular
.module('App', [])
.controller('AppController', ['$scope', '$document', function ($scope, $document) {
$scope.outputProductAttributeValueList = ['age', 'gender', 'all'];
$scope.onRankingFormSubmit = function () {
var inputs = $document[0].querySelectorAll('#rankingForm input');
inputs.forEach(function(input) {
console.log(input.name + ': ' + input.value);
});
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<div ng-app="App" ng-controller="AppController" class="row">
<br>
<div class="col-sm-10" id="rankingForm" >
<p ng-repeat="x in outputProductAttributeValueList">
{{x}} <input type="text" name="{{x}}" />
</p>
<br>
<button type="submit" ng-click="onRankingFormSubmit()">SUBMIT</button>
</div>
</div>
Code with ngModel:
angular
.module('App', [])
.controller('AppController', ['$scope', '$document', function ($scope, $document) {
$scope.outputProductAttributeValueList = ['age', 'gender', 'all'];
// Model inputs
$scope.inputs = {};
$scope.onRankingFormSubmit = function () {
$scope.outputProductAttributeValueList.forEach(function(input) {
// Access to model inputs: $scope.inputs[input]
console.log(input + ': ' + $scope.inputs[input]);
});
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<div ng-app="App" ng-controller="AppController" class="row">
<br>
<div class="col-sm-10" id="rankingForm" >
<p ng-repeat="x in outputProductAttributeValueList">
{{x}} <input type="text" ng-model="inputs[x]" />
</p>
<br>
<button type="submit" ng-click="onRankingFormSubmit()">SUBMIT</button>
</div>
</div>

Related

How access form in ng-repeat?

Here is clear exampel about forms:
<div ng-form="namesForm_{{$index}}" ng-repeat="name in names">
<input type="text"
name="input_{{$index}}_0"></input>
<!-- ... -->
Ok, but how I should access $valid field from form? E.g this does not work:
{{namesForm_$index.$valid}}
Even {{namesForm_$index}} outputs 0.
It is need to "inline" $index before {{}} resolve a variable name. How to do that?
It's not easy to get it inside of single {{ }} expression, but if you only want to use it in directives accepting expressions without handlebar (like ng-disabled), you can achieve that:
<div ng-app>
<ng-form name="namesForm_{{$index}}" ng-repeat="name in [1, 2]">
<input type="text"
placeholder="{{$index}}"
ng-required="true"
ng-model="test"
name="hey" />
<button ng-disabled="!namesForm_{{$index}}.$valid">
send
</button>
<br />
</ng-form>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
{{ IsFormValid($index) }}
$scope.IsFormValid = function(index) {
var form = angular.element("formName" + index);
return form.$valid;
};
UPDATED
Working example:
{{ IsFormValid($index) }}
$scope.IsFormValid = function(index) {
var form = angular.element(document.getElementById('#bucketForm-' + index);
return form.$valid;
};
New Approach
The below is an example for dynamic ngModel, same can be replicated for form name :
$scope.formData = {};
$scope.formData = {
settings:
{
apiEndpoint: '',
method: 'get'
},
parameters: {}
};
<div class="form-group" ng-repeat="parameter in apiParameters">
<label for="{{parameter.paramName}}" class="col-sm-2 control-label">{{parameter.paramTitle}}</label>
<div class="col-sm-3">
<input type="text" class="form-control" name="{{parameter.paramName}}" id="{{parameter.paramName}}" ng-model="formData.parameters[parameter.paramName]" placeholder="{{parameter.paramTitle}}">
</div>
</div>

How to display ng model value to another page

I have an html page with angular in which ng model returns a address and I want to display the same address in other html page. How to do it? And my code is
<input type="text" class="form-control" ng-model="Item" placeholder="Enter the IP Address"/>
You can do similarly like this:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$rootScope) {
$rootScope.$on('eventName', function(event, args) {
$scope.emitMessage = args;
});
})
.controller('myCtrl2', function($scope,$rootScope) {
$scope.onclick = function() {
$rootScope.$emit('eventName',{msg: 'my message'});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<p>Message Emitted: {{emitMessage.msg}}</p>
</div>
<div ng-controller="myCtrl2"
<button ng-click="onclick()"> click me to emit message</button>
</div>
</div>

filling a textarea with ng-repeat or ng-model so that it does not create a new textarea one on top of the other with the iterated data

im having issues trying to fill a single 10 row textarea with data using ng-repeat instead it creates a new textarea for every data entry. how can i just insert into one? and i would like to make the size of the textarea dynamic to the number of entries enterd by ng-repeat
this is my js file
var WaitingRequisitionsController = function($scope, $rootScope, $modal, $window, items) {
$rootScope.title = 'Direct Requisitions';
$scope.items = items;
$scope.formatDate = function (x) {
return moment(x).format("M/D/YYYY");
};
};
and this is my html file, specifically the area im trying to insert.
<div class="row ">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 col-xl-12">
<div class="form-group">
<label>Items</label>
<div ng-repeat="item in req.items">
<textarea ng-model="item.description" class="form-control" type="text" readonly="readonly"></textarea>
</div>
</div>
</div>
</div>
and this does the same thing
<div class="row ">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 col-xl-12">
<div class="form-group">
<label>Items</label>
<textarea ng-repeat="item in req.items" class="form-control" type="text" readonly="readonly">{{item.description}}</textarea>
</div>
</div>
</div>
i have changed my js to look like this
var WaitingRequisitionsController = function($scope, $rootScope, $modal, $window, items) {
$rootScope.title = 'Direct Requisitions';
//$scope.items = items;
$scope.formatDate = function (x) {
return moment(x).format("M/D/YYYY");
};
};
function TodoCtrl($scope) {
$scope.items = items.join('\n');
$scope.$watch('items', function (items) {
$scope.myArray = items.split('\n');
console.log('$scope.myArray', $scope.myArray);
});
}
and my html to look like this
<!-- <div class="row ">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 col-xl-12">
<div class="form-group" ng-app>
<label>Items</label>-->
<div ng-app>
<div ng-controller="TodoCtrl">
<textarea rows={{rows}} class="form-control" ng-model="myStr" type="text" readonly="readonly"></textarea>
</div>
</div>
<!-- </div>
</div>
</div>-->
but nothing populates if i change this around to look like this
http://jsfiddle.net/U3pVM/8165/
it works..i dont get it
i need item.description i dont know if that has anything to do with it
Join the items into a single string, separated by newlines
var WaitingRequisitionsController = function($scope, $rootScope, $modal, $window, items) {
$rootScope.title = 'Direct Requisitions';
$scope.items = items
.map(function (item) {
return item.description;
})
.join('\n');
$scope.rows = items.length;
$scope.formatDate = function (x) {
return moment(x).format("M/D/YYYY");
};
};
You can then use the length of the items array to set the number or rows on the text area.
<textarea type="text" class="form-controler readonly="readonly" rows="rows"
ng-model="items">
</textarea>
Plunker for example: http://plnkr.co/edit/SXSl4nHJi8ptufP6wTd4?p=preview
You're ng-repeating <textarea> (either in itself, or through a containing div) so that it iterates over each instance of item. What you need to do is get rid of the ng-repeat all together and use ng-model to concatenate a string, as demonstrated in ajs's answer.

Controller and input form html use var Javascript

I use the angularjs framework, I created an form.html and a controller.js with a variable that retrieves the SSID of a box.
How to automatically assign the value of the variable in the form.
This is an input field.
When launching the application, the form should display the SSID automatically without the user needing to do so.
Thank you kindly help me.
'use strict';
angular.module('djoro.controllers')
.controller('WifiSmartConfigCtrl', function ($scope, $window, $ionicPlatform) {
$scope.getSSID = function () {
var onSuccess = function (SSID) {
document.write(SSID);
};
var onFail = function () {
};
$ionicPlatform.ready(function () {
$window.cordova.plugins.Smartconfig.getSSID(onSuccess, onFail);
});
};
});
<ion-pane>
<ion-content ng-controller="WifiSmartConfigCtrl">
<form novalidate class="simple-form">
<fieldset>
<legend>WI-FI</legend>
<div class="list input-fields">
<label class="item item-input">
<span class="input-label">SSID :</span>
<input type="text" name="test" value="getSSID()" required show-hide-input>
</label>
<label class="item item-input" show-hide-container>
<span class="input-label">Password :</span>
<input type="text" name="password" required show-hide-input>
</label>
</div>
</fieldset>
</form>
</ion-content>
</ion-pane>
use the ng-model directive, it's exactly it's purpose :
'use strict';
angular.module('djoro.controllers')
.controller('WifiSmartConfigCtrl', function($scope, $window, $ionicPlatform) {
$scope.SSID = {};
$scope.getSSID = function() {
var onSuccess = function(SSID) {
$scope.SSID = SSID;
};
var onFail = function() {};
$ionicPlatform.ready(function() {
$window.cordova.plugins.Smartconfig.getSSID(onSuccess, onFail);
});
};
});
and in your view :
<input type="text" name="test" ng-model="SSID" required show-hide-input>
You need to add an ng-model to the input field like so:
<label class="item item-input">
<span class="input-label">SSID :</span>
<input type="text" name="test" ng-model="SSID" required show-hide-input>
</label>
then in your controller assign the value of SSID on the $scope:
$scope.SSID = [some_value]
see this plnkr
As you can see I have assigned the value of SSID manually, you can add it dynamically by assigning it in the callback of your function like so:
$scope.SSID = {}
var onSuccess = function (SSID) {
document.write(SSID);
$scope.SSID = SSID
};

ng-model in ng-repeat become undefined

Using Javascript with angularJs, I kind the following code :
JS
$scope.myObj = {
'sthg': '',
'a': [{
'b' : ''
}]
}
HTML
<p ng-repeat="radio in fiche.radios">
<input type="text" ng-model="radio.code" placeholder="Numéro de cliché" ng-required="true" />
<span >
<button type="button"ng-click="removeRadioList($index);" ng-disabled="fiche.radios.length === 1">
<i>X</i>
</button>
</span>
</p>
http://plnkr.co/edit/LOgk7Nudse0srS7Bs1G6?p=preview
In my App $scope.myObj.a[0].b is undefined with the ng-repeat (if I remove ng-repeat, it will be defined).
In the plunkr it is defined even after the run of ng-repeat, but I managed to have the behaviour when I enter something in the input and then delete it.
I don't get what's hapening, I would like to understand why and if it is a good way to do ?
Beacause you set ng-required="true" on your input tag angular wouldn't bind empty value to your model thous when you delete value from input your console shows you radios.code as undefined.
Please see below for working demo:
(function() {
"use strict";
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $log) {
$scope.ficheInit = {
'user_id': '',
'radios': [{
'code': ''
}]
};
$log.log($scope.ficheInit);
$scope.fiche = angular.copy($scope.ficheInit);
$log.log($scope.fiche);
$scope.addRadioList = function() {
$scope.fiche.radios.push({
'code': ''
});
}
$scope.removeRadioList = function(i) {
$scope.fiche.radios.splice(i, 1);
}
$scope.disableAddRadio = function() {
console.log($scope.fiche.radios);
return !(angular.isDefined($scope.fiche.radios[$scope.fiche.radios.length - 1].code) || $scope.fiche.radios.length < 1);
}
});
}());
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="plunker">
<div ng-controller="MainCtrl">
<button ng-click="showForm=true;">SHOW</button>
<div ng-show="showForm">
<button ng-click="addRadioList();" ng-disabled="disableAddRadio()">Ajouter un cliché</button>
<p ng-repeat="radio in fiche.radios">
<input type="text" ng-model="radio.code" placeholder="Numéro de cliché" />
<span>
<button type="button" ng-click="removeRadioList($index);" ng-disabled="fiche.radios.length === 1">
<i>X</i>
</button>
</span>
</p>
</div>
{{fiche.radios}}
</div>
</div>

Categories