I'm building a dynamically generated form from a database using ng-repeat in Node.js and Angular. All of the text boxes are replicating the text entered on any one of the text boxes. So, if I type "xyz" in one text box, all of them have "xyz". But, if I submit the results, it only updates that one form reference.
This is the HTML:
<div class="container">
<div class="todo-form">
<form class="form-inline" ng-repeat="todo in todoData">
<li>
<h4>Country Code: {{ todo.country_code }} <input id="{{ todo.country_code }}" type="text" class="form-control input-sm" placeholder="{{ todo.country_name }}" ng-model="formData.text">
<button type="submit" class="btn btn-default" ng-click="updateTodo(todo.country_code)">Update</button></h4><br>
</li>
</form>
</div>
This is the JS it refers to:
angular.module('editTodo', [])
.controller('editController', ($scope, $http) => {
$scope.formData = {};
$scope.todoData = {};
// Get Org Details
$http.get('ref_country_code_get')
.success((data) => {
$scope.todoData = data;
console.log(data);
})
.error((error) => {
console.log('Error: ' + error);
});
Clearly, I need to disable this. I've tried to add a name= or ID={{ todo.country_code }} into the form to make it unique, but that doesn't work. Why are the all acting like they are the same text box? I'm new to Node.js and very rusty with my HTML, but I can't find any reference to this phenomena. Maybe it is too basic that nobody makes this mistake? %)
Andy F solved the issue. Simply replace the ng-model="formdata.txt" to ng-model="todo.txt". Now, none of the text boxes replicate what is typed in any other text box.
Related
In my Project i Got a Issue like.I need to bind the user hobbies in the text field.if the user comes with a single hobby he can directly enter the hobby that he has. but when he had multiple then he had to click add multiple hobbies button.that working fine when i am displaying input fields dynamically using directives.but the issue is the value that coming from ng-model for that input field is binding to all input fields.
Here is my code.
Thanks in advance!
these are the images
this is how i am getting
this is what i need
In HTML
<div>
<div id="showHobbyfield"></div>
<input type="number" class="form-control" placeholder="ADD HOBBIES"
ng-click="addHoby()">
</div>
In controller
$scope.addHoby= function(){
var compiledeHTML = $compile("<div my-hobby></div>")($scope);
$("#showHobbyfield").append(compiledeHTML);
};
$scope.addUser = function(){
$scope.Users= [];
var obj = {
userhobby : $scope.user.morehobies
};
$scope.Users.push(obj);
menuStorage.put($scope.Users);
//menustorage is service to store user in localStorage.
In directive
'use strict';
angular.module('myApp')
.directive('myHobby', function() {
return {
scope : false,
templateUrl: 'views/my-hobby.html'
};
});
this is template: my-hobby.html
<div class="input-group">
<input type="text" ng-model="user.morehobies" class="form-control" placeceholder="type your hobbies here">
<div class="close-icon">
<span class="glyphicon glyphicon-remove" style="padding-left: 6px;"> </span>
</div>
</div>
For this i would suggest some other way if its ok with you.
If your hobbies is coming in array, like
user.morehobies = ['Reading', 'Writing']
or create array for storing hobbies.
then inside directive you can pass that object in directive.
I will use ng-repeat inside directive.
<div class="input-group" ng-repeat="h in hobies">
<input type="text" ng-model="h" class="form-control" placeceholder="type your hobbies here">
<div class="close-icon">
<span class="glyphicon glyphicon-remove" style="padding-left: 6px;"> </span>
</div>
</div>
so whenever user clicks on "Add hobbies" then we can add empty string in hobbies object in directive.
and whenever user clicks on remove you can remove that item from array.
I use this lib to create table on page.
Every row in this table can be edited. So if editMode is on, I show inputs at each column of row. Some of this inputs is required. I want to show red text "Required" or just red border if required field is empty.
But problem - it's simple when I use form. But in my case I can't use forms.
This answer isn't good for me, cause every row must have unique form-name for correct validation.
Example : https://jsfiddle.net/r8d1uq0L/147/
<div ng-repeat="user in users">
<div name="myform-{{user.name}}" ng-form>
<input type="text" ng-model='user.name' required name="field"/>
<span class="error" ng-show="myform.field.$error.required">Too long!</span>
</div>
</div>
<div>
<button ng-click="add()">
Add
</button>
</div>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.users = [{name:"1"}, {name:"2"}];
$scope.add = function(){
$scope.users.push({});
}
});
No need to create a dynamic form name, as ng-repeat does create new child scope on each iteration while drawing template on browser. So just keep name as name="innerForm" and use innerForm.field.$error.required to have validation over it.
<div ng-repeat="user in users">
<div name="innerForm" ng-form>
<input type="text" ng-model='user.name' required name="field"/>
{{myform[$index]}}
<span class="error" ng-show="innerForm.field.$error.required">Too long!</span>
</div>
</div>
Forked Fiddle
I am new to Angular and I was trying my hands on a few functions. I found this strange behavior when I try to re-enter the same value.
<!-- HTML -->
<body ng-app="angular-test">
<div ng-controller="FormController">
<ul>
<li ng-repeat="name in names">{{name}}</li>
</ul>
<form ng-submit="addName()">
<input type="text" ng-model="newName">
<input type="submit" value="Add">
</form>
</div>
</body>
/*** Angular Code ***/
(function() {
var app = angular.module("angular-test", []);
app.controller("FormController",formController);
function formController($scope){
$scope.names = ['Israel','Agyeman','Prempeh','Osei','Apea'];
$scope.addName = function(){
$scope.names.push($scope.newName);
$scope.newName = '';
}
}
})(angular);
![A list generated from the existing model in the HTML page][1]
Israel
Agyeman
Prempeh
Osei
Apea
King
king
______________ [Add] (input form)
"King" was added through the add button so was "king" but as I typed "king" again it failed to update and does not update afterwards no matter what I insert. Any ideas as to what is causing this?
Evening Israel,
You can't duplicate values in a repeater. To make it works, just add the following:
name in names track by $index
Or see it in action: http://codepen.io/anon/pen/xGzRKK
Hope it helps!
I am having difficulty with a javascript that I need some help with. I have a form which sends to a php the exact amount of inputs to be filled, now I want to create a preview using jQuery/javascript but how can I catch all the fields dynamically.
Here is a portion of my form for reference:
<td>
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-pencil"></i></span>
<input class="form-control" id="task" type="text" name="task" placeholder="Task Title">
</div>
</td>
<td>
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-pencil"></i>
</span>
<input class="form-control" id="description" type="text" name="description" placeholder="Task Description">
</div>
</td>
So, I added in PHP the name field + the number, this way I can get different names ie: task1, task2,...etc.
Now what I need to do is get the values using jQuery/javascript.
My thoughts so far is to declare the var (variable) inside a for() (loop)
var task = $('input[name=task]').val();
How can I get all values task1, task2. No one knows how many task fields the user will submit so I need to get the number of fields
Any help direction so I can figure this out
First of all, you don't need to give your input fields names like task1, task2, etc to distinguish among them on the server-side i.e on the PHP. You just need to give all of them a name attribute value like tasks[] And notice the brackets [] so you may have something like the following:
<input class="form-control" id="tasks[]" type="text" name="tasks[]" placeholder="Task Title">
...
<input class="form-control" id="tasks[]" type="text" name="tasks[]" placeholder="Task Title">
Like that automatically values in those fields will be posted as an array to the PHP and it is going to be received like the following in PHP script:
$tasks = $_POST['tasks'];
foreach ($tasks as $task){
echo $task;
}
Second By this way you will easily able to collect your inputs data using Javascript inorder to generate the preview by using getElementsByName method as follows:
function preview(){
output = "";
tasks = document.getElementsByName('tasks[]');
for (i=0; i < tasks.length; i++){
output += "<b>Title</b>: "+tasks[i].value+"<hr />";
}
panel = document.getElementById('panel');
panel.innerHTML = output;
}
Of course you can expand this solution to any number of fields in your form such as descriptions[].
A javascript DEMO: http://jsbin.com/kiyisi/1/
Using the Attribute Starts With Selector [name^="value"] and jQuery.each()
var tasks = $('input[name^=task]').val();
$.each(tasks,function(index, value){
//do something with the value
alert($(this).val());
});
edit
var tasks = $('input[name^=task]');
$.each(tasks,function(index, value){
//do something with the value
$('#Preview').append($(this).val());
});
Q: now I want to create a preview using jquery/javascript but how can I catch all the fields dinamically:
If you give them a class, you can get all fields with each:
$(".className").each(function() {
do something
Next, "catch" all fields... I'm assuming you may want the values of these fields too? Check this example for details, here is a snippet which loads the key:value pairs (form field name : value of field) into a map:
var map = {};
$(".activeInput").each(function() {
map[$(this).attr("name")] = $(this).val();
});
Print all values inside div (Here, I'm assuming you're talking about children values of div):
<div>
<span>Hi</span>
<span>Hello</span>
<span>Hi again</span>
</div>
$("div").children().each(function () {
console.log($(this).text());
});
OR
$("div span").each(function () {
console.log($(this).text());
});
I am using Angular 1.0.8 along with Restangular for this. Since I am just starting out in js framework in general, a newbie-friendly explanation would be greatly appreciated.
I have a very simple HTML <section> like this (ng-app has been defined in body):
<section class="comment-list block scrollable wrapper" style="height:350px" ng-controller="MessageStreamController">
<div> {{ message.message }} </div>
<div class="input-group">
<input type="text" class="form-control" ng-change="change()" ng-model="message.message" placeholder="Input your comment here">
<span class="input-group-btn">
<button class="btn btn-primary" type="button" ng-click="clicked()">POST</button>
</span>
</div>
</section>
with the following <script>
var JApp = angular.module('JApp', ['restangular']);
JApp.controller('MessageStreamController', function($scope, Restangular) {
var service = Restangular.all('message-stream');
$scope.clicked = function() {
$scope.message = service.one('index', 1).get();
}
})
In the backend /message-stream/index/1 it simply returns
return json_encode(array(
'message' => 'Hey there James',
'user' => 'Terry'
));
This results in the <div> {{ message.message }} </div> and input gets rendered with 'Hey there James'. All good so far.
But then I can't edit the input box afterwards.
Some questions pointed out that this happens when you don't use ng-repeat, but then again I am expecting one JSON object from the backend.
Any pointer here to help?
UPDATE:
Changed from Restangular to $resource fixes my problem. Though would love to know why this is happening. Answer from people who has experience with Restangular will be appreciated.
Restangular returns a promise from all queries which can not be edited.
Instead you should assign the actual result to your scope as per the answer to this question - Angular.JS: why can't the inputs be edited?