Button inside ng-repeat to update input in form - angularjs

What I am trying to do is update an input field from within an ng-repeat. I have an ng-click on the button inside the ng-repeat for each user. When clicking on the button it should update the value of the input field which is outside the ng-repeat but in the same controller. I have just started using Angularjs and I seem to be missing something simple here, but just can't figure it out. Any help is greatly appreciated!
<div ng-app="MyApp">
<div ng-controller="Main">
<form name="myForm">
<input type="email" ng-model="rootFolders">
<button type="submit">Submit</button>
</form>
<span ng-repeat="user in users" style="float:left">
{{user.name}}<br>
<button ng-click="rootFolders='{{user.login}}'">Load Email</button>
</span>
</div>
</div>
Controller
angular.module('MyApp', []);
function Main($scope) {
$scope.rootFolders = 'bob#go.com';
$scope.users = [
{id:0,name:'user1',login:'user1#go.com',password:'123456'},
{id:1,name:'user2',login:'user2#go.com',password:'123456'},
]
}
Here is the fiddle: http://jsfiddle.net/DahDC/

You need to create a ng-click action in scope and pass in the user for current row.
<div ng-app="MyApp">
<div ng-controller="Main">
<form name="myForm">
<input type="email" ng-model="rootFolders">
<button type="submit">Submit</button>
</form> <span ng-repeat="user in users" style="float:left">
{{user.name}}<br>
<button ng-click="loadEmail(user);">Load Email</button>
</span>
</div>
</div>
angular.module('MyApp', []);
function Main($scope) {
$scope.rootFolders = 'bob#go.com';
$scope.users = [{
id: 0,
name: 'user1',
login: 'user1#go.com',
password: '123456'
}, {
id: 1,
name: 'user2',
login: 'user2#go.com',
password: '123456'
}, ]
$scope.loadEmail = function (user) {
$scope.rootFolders = user.login;
}
}
Try it. FIDDLE

I believe that because you are making the assignment inside ng-click inside ng-repeat, it is assigning the rootFolders property on the local scope there (the one instantiated by ng-repeat for each element). So your actually assigning a new property on all the local scopes of ng-repeat.
I've edited your fiddle to explicitly show this. A good learning point!
<div ng-app="MyApp">
<div ng-controller="Main">
<form name="myForm">
<input type="email" ng-model="rootFolders"> {{ rootFolders }}
<button type="submit">Submit</button>
</form>
<span ng-repeat="user in users" style="float:left">
{{user.name}}<br>
<button ng-click="rootFolders = user.login">Load Email {{ user.login }}</button><br/>
{{ rootFolders }}
</span>
</div>

Related

input ng-model within ng-repeat

I am repeating a list of tasks that I would like other users to be able to comment on using an input field. I repeat the list with ng-repeat and am trying to send the value of the comment input to the server with ng-model and scope. I am testing by console logging but it shows as undefined. Please help!
Html:
<div class="taskContainer">
<div ng-repeat='task in taskList' class="task">
<div class="postedBy">
<h6>{{task.user.userName}}</h6>
</div>
<h4>{{task.taskText}}</h4>
<div class="comments">
<input ng-model="newComment" type="text" placeholder="comments">
<button ng-click='comment(task.taskId)' type="button" name="button">Add</button>
<h6>{{task.commentText}}</h6>
</div>
</div>
</div>
JS controller:
$scope.comment = function(id,text){
console.log(`send comment text ${$scope.newComment}`);
console.log(`task Id: ${id}`);
};
This is the first time I've tried to do more than display itmes with ng-repeat
You're getting undefined because ngRepeat creates its own $scope.
Always assign ngModel using Dot Rule or controller-as-syntax.
Put it in your controller:
$scope.model = {};
Then use the ngModel as this:
<input ng-model="model.newComment[$index]" type="text" placeholder="comments">
Then you can have something like this:
<div class="taskContainer">
<div ng-repeat="task in taskList track by $index" class="task">
<div class="postedBy">
<h6>{{task.user.userName}}</h6>
</div>
<h4>{{task.taskText}}</h4>
<div class="comments">
<input ng-model="model.newComment[$index]" type="text" placeholder="comments">
<button ng-click='comment($index)' type="button" name="button">Add</button>
<h6>{{task.commentText}}</h6>
</div>
</div>
</div>
$scope.comment = function(index) {
console.log(`send comment text ${$scope.model.newComment[index]}`);
console.log(`task Id: ${taskList[index].id}`);
};
Note: Your function is expecting 2 parameters, you should change it to:
$scope.comment = function(id) {
Thanks for the help from #developer033.
Here is what solved my problem:
HTML:
<div class="taskContainer">
<div ng-repeat="task in taskList track by $index" class="task">
<div class="postedBy">
<h6>{{task.user.userName}}</h6>
</div>
<h4>{{task.taskText}}</h4>
<div class="comments">
<input ng-model="model.newComment[$index]" type="text" placeholder="comments">
<button ng-click='comment(task.taskId,$index)' type="button" name="button">Add</button>
<h6>{{task.commentText}}</h6>
</div>
</div>
</div>
and the JS:
$scope.model = {};
$scope.comment = function(id, index) {
console.log(`send comment text ${$scope.model.newComment[index]}`);
console.log(`task Id: ${id}`);
};
HTML,
<input ng-model="newComment" type="text" placeholder="comments">
<button ng-click='comment(task.taskId, newComment)' type="button" name="button">Add</button>
JavaScript,
$scope.comment = function(id, text) {
console.log(`task Id: ${id}`);
console.log(`send comment text ${text}`);
};

How to submit current form in ng-repeat angularjs

I need am not able to access the $scope.mainform.subform.submitted property in my script. My html goes as below.
<div ng-form="mainform">
<div ng-repeat="dependent in DependentDetails">
<ng-form name="subform">
<input type="text" class="textbox" ng-model="dependent.FirstName"/>
#*Same goes for other personal details*#
<input type="button" id="submitbutton" value="Save" ng-model="Submit" ng-click="saveDependentDetailsClick($event, $index, dependent)" />
</ng-form>
</div>
</div>
Can anyone help?
First of all, I think that it's not correct to use <ng-form name="subform">...</div> in ng-repeat in a way you have used it because you will end up with multiple forms having same name(subform) within the same scope therefore you can't refer to each of these forms as they have not unique name providing you with reference to them.
You will also end up with multiple submit buttons with the same id="submitbutton" in same html document which is an invalid html.
try this.
var app = angular
.module('MyApp', [
])
.controller('Main', ['$scope', function ($scope) {
$scope.DependentDetails = [{"FirstName":""},{"FirstName":""}];
$scope.saveDependentDetailsClick = function(DependentDetails){
console.log(DependentDetails);
}
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="main-content" ng-app="MyApp" ng-controller="Main as myCtrl">
<div ng-form="mainform">
<div ng-repeat="dependent in DependentDetails">
<ng-form name="subform">
<input type="text" class="textbox" ng-model="dependent.FirstName"/>
<input type="button" value="Save" ng-click="saveDependentDetailsClick(dependent)" />
</ng-form>
</div>
</div>
</div>

Set validation for dynamic field

I have a form where the user can add fields dynamically. It is my html:
<body ng-controller="FruitController">
<button type="button" ng-click="addFruit()">Add fruit</button>
<form name="list">
<div id="dynamicList" ng-repeat="fruit in fruits">
<input type="text" name="fruitName" ng-model="fruit.name" ng-minlength="3"/>
</div>
</form>
</body>
And it is my controller:
app.controller('FruitController', [function(){
$scope.fruits = [
{name: 'Apple', color: 'red'}
];
$scope.addFruit = function()
{
$scope.fruits.push({name: '', color: ''});
};
}]);
So, when a field is invalid i add a css class with the next directive:
ng-class="{'uk-form-danger': (list.fruitName.$invalid && !list.fruitName.$pristine)}"
The problem is that, when 1 field fails, another fields too.
Any ideas ?
Form inside ng-repeat won't work directly. You need to create a a separate form for inner elements that form will be child of outer form list
<form name="list">
<div id="dynamicList" ng-repeat="fruit in fruits">
<form name="innerForm">
<input type="text" name="fruitName" ng-model="fruit.name" ng-minlength="3"
ng-class="{'uk-form-danger': (innerForm.fruitName.$invalid && !fruit.name.$pristine)}"/>
</form>
</div>
</form>

How to prepend content of a form on form submit using AngularJS

I am trying to learn angularJS and have problem figuring out how to solve this issue. I am trying to prepend content of the form when user submit the form. This is my code but it's not working. Can anyone help me to figure out where the problem is? Thanks!
angular.module("displayText", [])
.controller("submitText", function($scope) {
$scope.outputArr = [];
$scope.print = function() {
$scope.outputArr.push($scope.inputText);
$scope.inputText = '';
};
};
});
<body ng-app="displayText">
<div ng-controller="submitText">
<form method="get" action="#">
<input type="text" name="input" ng-model="inputText" required/>
<button ng-click="print(inputText)">Submit</button>
</form>
</div>
<div>
<p ng-repeat="text in outputArr">{{text}}</p>
</div>
</body>
put this piece of code inside the submitText controller div
<div>
<p ng-repeat="text in outputArr">{{text}}</p>
</div>
then you whole code should be like
<div ng-controller="submitText">
<form method="get" action="#">
<input type="text" name="input" ng-model="inputText" required/>
<button ng-click="print(inputText)">Submit</button>
</form>
<div>
<p ng-repeat="text in outputArr">{{text}}</p>
</div>
</div>
here is the Plunker
in your case the ng-repeat="text in outputArr" is out of the controller that means scope of the submitText controller not accessible for the ng-repeat that's why its not print anything

Issue with ng-model and ng-repeat, input value is duplicated on each form field on the page

I have a page where multiple forms are created based on ng-repeat. everything works fine until write something into the input and everything gets duplicated on all the other repeated forms input elements. I have used ng-model="Notify.message" which is nothing but object which takes the value from the input and sends to control on button submit and hence rest of the logic.
I am looking for when if one form is been filled, other forms should keep quite and shouldnt duplicate the values written in input text of form 1.
Here is the code:
<div data-ng-show="alluserposts.length > 0">
<div id="b{{userpost.id}}" data-ng-repeat="userpost in alluserposts" >
<div class="row" style="margin-left: -5px">
<form class="text-center" role="form" id=f1{{userpost.id}} name="userForm"
ng-submit="notify(userForm.$valid, userpost, apiMe)" novalidate>
<div class="row">
<div class="col-xs-8 col-md-4">
<div class="form-group">
<input data-container="body" data-toggle="popover" data-placement="top"
data-content="Any message which you would like to convey to post owner"
type="text" ng-model="Notify.message" data-ng-init="Notify.message=''"
id="u{{userpost.id}}"
placeholder="Enter a Message or Phone number" class="form-control"
required>
<p ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block">It is
required.</p>
<script>$(function () {
$("[data-toggle='popover']").popover();
});
</script>
<input type="hidden" ng-model="Notify.loggedInEmail"
ng-init="Notify.loggedInEmail = result.email"/>
<input type="hidden" ng-model="Notify.postId" ng-init="Notify.postId = userpost.id"/>
<input type="hidden" ng-model="Notify.destEmail"
ng-init="Notify.destEmail = userpost.userEmail"/>
</div>
</div>
<div ng-show="loginStatus.status == 'connected'" class="col-xs-4 col-md-2">
<button class="btn btn-primary" ng-disabled="userForm.$invalid || !userForm.$dirty"
type="submit">
Notify Post Owner
</button>
</div>
</div>
</form>
</p>
</div>
</div>
</div>
</div>
I will attempt following solution to implement it.
create a nested json object with number of forms to display in angularjs controller.
for example
$scope.FormsCollection = {
"Form1" : [
{"title" : "Rockband", "details" : "1hr"},
],
"Form2" : [
{"title" : "The Old You", "details" : "Dr. Smith"}
]
}
obviously, you can use loop to build it or whatever approach suits you best in your context to build the forms collection in angularjs controller.
then in html page you can use following convention to correctly populate each form data
you need two ng-repeat, first for index of each form, and then to iterate nested form object.
<input type="text" ng-model="form[index].firstName"/>
as result you will have $scope.FormsCollection with correct form object data
Please check the example code in following jsfiddle
http://jsfiddle.net/CMnxW/4/
jsfiddle should contain following code.
<div ng-app>
<div ng-controller="controller">
<ul ng-repeat="post in posts">
<li>{{$index}}
<input type="text" ng-model="post.userEmail" />
<button class="btn btn-danger" ng-click="notify(post)" type="button">Notify</button>
</li>
</ul>
<table>
<tr>
<td>destEmail is: </td>
<td>{{Notify.destEmail}}</td>
</tr>
</table>
</div>
</div>
JS:
function controller($scope) {
$scope.Notify = {
destEmail: ''
};
$scope.posts = [{userEmail: 'e#mail.com'}, {userEmail: 'f#mail.com'}];
$scope.notify = function(post) {
$scope.Notify.destEmail = post.userEmail;
//set other $scope.Notify properties from post
//your other notify code...
}
}

Resources