How to set same value for all the textboxes in an unordered list in angular js? - angularjs

Suppose i have 5 textboxes in a list.I enter text input in the first text box and click send. Now i want the input value entered to be showed in all the other textboxes in the list.
Following is my html code:-
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Plunker</title>
<script src="./scripts/angular.min.js"></script>
<script src="./scripts/app.js"></script>
</head>
<body ng-app="chatApp">
<div ng-controller="chatController">
<ul>
<li ng-repeat="chat in chats">
<input type="text"/>
<button ng-click="sendChat()">Send</button>
<button ng-click="deleteChat($index)">Delete</button>
</li>
</ul>
<button ng-click="addChat()">Click me to add</button>
</div>
</body>
</html>
Following is my angular code:-
var app=angular.module('chatApp',[]);
app.controller('chatController',['$scope',function($scope){
$scope.chats=[];
$scope.addChat = function() {
if($scope.chats.length<10)
{
$scope.chats.push({name:''});
}
}
$scope.deleteChat=function(index){
$scope.chats.splice(index,1);
}
$scope.sendChat=function(data){
}
}]);
I have a sendChat function where i was thinking to put the code.

Add model in your input field
<input type="text" ng-model="chat.msg"/>
Then pass the selected msg
<button ng-click="sendChat(chat)">Send</button>
Then assign msg in other textboxes
$scope.sendChat = function(data) {
$scope.chats.map(function(x) {
x.msg = data.msg;
})
}
DEMO

Related

How to add text from textbox in angularjs1

I have written a code for adding messages to the page below the textbox. The text box has an add button . As soon i write a message in the textbx and click on add, the message should appear on the next line. I have used ng-repeat to repeat the process of adding messages whenever the add button is clicked. However i am getting error messages -
Expression 'addMessage()' is non-assignable.
And Error -
angular.js:13283 ReferenceError: message is not defined.
Please help me with the code.
<html ng-app="Swabhav.Message">
<head>
<title>message-app</title>
<script src="angular.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/bootstrap.min.js"></script>
</head>
<body>
<div ng-controller="MessageAdd">
<h3>To Add Message:</h3>
<input text="text" ng-model="addMessage()">
<li ng-repeat="mess in message">
<button type="button" ng-click="addMessage()">Add</button>
</li>
<br>
<li><p> {{mess}}</li>
</p><br>
</div>
<script>
angular.module("Swabhav.Message", [])
.controller("MessageAdd", ["$scope", function($scope) {
$scope.message = [];
$scope.addMessage = function() {
$scope.message.push(message);
};
}]);
</script>
</body>
</html>
Try it:
HTML
<body>
<div ng-controller="MessageAdd">
<h3>To Add Message:</h3>
<input text="text" ng-model="messagetext">
<button type="button" ng-click="addMessage()">Add</button>
<li ng-repeat="mess in message">{{mess}}</li>
</div>
</body>
CONTROLLER:
angular.module("Swabhav.Message",[])
.controller("MessageAdd",["$scope",function($scope){
$scope.messagetext = "";
$scope.message=[];
$scope.addMessage =function(){
$scope.message.push($scope.messagetext);
$scope.messagetext = "";
}
}]);
You have some errors.
First, you can't assign a function to a model. You have to add te value on your model to the array of messages. Then your button has to be before the ng-repeat or you will have one botton for each element on the list and {{mess}} inside the ng-repeat.
<input text="text" ng-model="message">
<button type="button" ng-click="addMessage()">Add</button>
<ul>
<li ng-repeat="mess in messages">
{{mess}}
</li>
</ul>
In your controller I would rename the array to messages and assign a empty array to your model.
$scope.messages=[];
$scope.message = "";
$scope.addMessage =function(){
$scope.messages.push($scope.message);
$scope.message = "";
}
Try this code and tell me if it is what you are trying to do and if you understand the code
Jsfddle

AngularJS app go back to inital state automatically

Following app shows three todo items at first and
after adding an new data, it shows updated lists for a moment and go back to the original state.
Could you tell me why does it go back to the initial state automatically?
link for Pluker
http://plnkr.co/edit/h6THusBe7AWFle5ixXzX?p=preview
==================================
<!DOCTYPE html>
<html ng-app="initExample">
<head>
<link data-require="bootstrap-css#*" data-semver="3.3.1" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<script src="https://code.angularjs.org/1.4.0-beta.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body class="well" ng-controller="ExampleController">
<h1> AngularJS Todo List</h1>
<p> Total <strong> {{todolist.length}} </strong> / Remain <strong> {{countRemain()}} </strong> </p>
<ul>
<li ng-repeat="todo in todolist" class="checkbox"> <input ng-model="todo.done" type="checkbox"> {{todo.title}}</li>
</ul>
<form name="newItemForm" class="form-inline" action="">
<div class="form-group">
<label class="sr-only" for="newItemText" placeholder="Type new ToDo"></label>
<input type="text" class="form-control" ng-model="newTodo" name="newItemText" placeholder="Type new Todo">
</div>
<button type="submit" ng-click="addNewTodo(newTodo)" class="btn btn-default"> Add </button>
</form>
</body>
</html>
============================
// Code goes here
var mymodule=angular.module('initExample', []);
mymodule.controller('ExampleController',
['$scope', function($scope) {
$scope.todolist = [
{done: true, title:'AngularJS study'},
{done: false, title:'music listening'},
{done: false, title:'run'}
];
$scope.countRemain = function() {
var count = 0;
var list = $scope.todolist;
angular.forEach(list, function(val, key) {
if(!list[key].done) count++;
});
return count;
};
$scope.addNewTodo = function(newTodo) {
todolist.push({done: false, title: newTodo});
};
}
]
);
Remove the action attribute from the form or add "preventDefault" from the button click.
Fixed the plunkr:
<form name="newItemForm" class="form-inline">
http://plnkr.co/edit/KFpbbdlDPbnIPAW43EaG?p=preview
P.S. also fixed the addNewTodo Function:
$scope.addNewTodo = function(newTodo) {
$scope.todolist.push({done: false, title: newTodo});
};
You need to remove action attribute from form definition, otherwise browser will try to submit it, reloading the page:
<form name="newItemForm" class="form-inline">
<!-- ... -->
</form>
Demo: http://plnkr.co/edit/MwTmGqzdELzUbrY82kKg?p=preview

Generate dynamic form input fields and collect field data in an array

I am stuck with this little task.
I need to generate form input fields dynamically by clicking 'add' button on the form.
The form is supposed to create DB table schema. So every input field is a DB table field name.
I am OK generating the fields dynamically but have trouble with gathering the actual data.
<form ng-controller="NewTableCtrl" ng-submit="submitTable()">
<input type='text' ng-model='table.title' placeholder='Title:'>
<input ng-repeat="field in fields" type='text' ng-model='table.fields' placeholder='Field:'>
<div>
<button type='submit'>Submit</button>
<button ng-click="addFormField()">Add</button>
</div>
</form>
.. and the controller
.controller('NewTableCtrl', function($scope) {
$scope.fields = [];
$scope.table = {};
$scope.addFormField = function () {
$scope.fields.push({});
}
$scope.submitTable = function () {
console.log($scope.table);
}
});
Looks simple. When I click 'Add' button it generates the new input field but it does it with the same model object (obveously). And that's where my misunderstanding lies. I thought that if I declare $scope.fields = [];in the controller then repeating field data will just go into the array. But it just echoes the input in every repeating input field. I understand now that this is how it is supposed to be with two way binding.
The reason I thought like this is by the analogy with an ordinary form submission where the repeating input field names become an array in the URL encoded form data.
So how do I solve this? The server needs to get an array of fields like this: fields: [field1, field2 ...] Do I need to generate input fields with different scope variable for each field? How do I do this?
Is this more complex then I thought and it needs to be a directive? If yes, please, show me how to do this.
Thanks.
Right now you are iterating $scope.fields. When you are adding a new field you push an empty object into $scope.fields, but every input's ng-model points to $scope.table.fields (which is non-existing until first input writes to it - then it will hold a string variable).
For this simple use case you could try:
app.controller('NewTableCtrl', function($scope) {
$scope.table = { fields: [] };
$scope.addFormField = function() {
$scope.table.fields.push('');
}
$scope.submitTable = function() {
console.log($scope.table);
}
});
And:
<input ng-repeat="field in table.fields track by $index" type='text' ng-model='table.fields[$index]' placeholder='Field:'>
Demo: http://plnkr.co/edit/6iZSIBa9S1G95pIMBRBu?p=preview
Take a look at this
Working Demo
html
<body>
<div ng-app=''>
<div ng-controller="questionCtrl">
<div>
<ul>
<li ng-repeat="elemnt in questionelemnt">
<div>
<div id={{elemnt.id}} style="display:inline" >
<span ng-model="elemnt.question" ng-hide="editorEnabled" ng-click="editorEnabled=true">
{{elemnt.question}}
</span>
<div ng-show="editorEnabled">
<input ng-model="elemnt.question" ng-show="editorEnabled" >
<button href="#" ng-click="editorEnabled=false">Done editing</button>
</div>
</div>
<div style="display:inline">
<span>
<input type="text" ng-model="elemnt.answer" placeholder="Answer" required/>
</span>
</div>
<span ng-hide="elemnt.length == 1">
<button ng-click="questionelemnt.splice($index, 1)">Remove</button>
</span>
</div>
<hr/>
</li>
<li>
<button ng-click="addFormField($event)">Add</button>
</li>
</ul>
</div>
<div>
<button ng-click="showitems($event)">Submit</button>
</div>
<div id="displayitems" style="visibility:hidden;">
{{questionelemnt}}
</div>
</div>
</div>
</body>
script
function questionCtrl($scope) {
var counter = 0;
$scope.questionelemnt = [{
id: counter,
question: 'Question-Click on me to edit!',
answer: ''
}];
$scope.addFormField = function ($event) {
counter++;
$scope.questionelemnt.push({
id: counter,
question: 'Question-Click on me to edit!',
answer: ''
});
$event.preventDefault();
}
$scope.showitems = function ($event) {
$('#displayitems').css('visibility', 'none');
}
}
Variation of tasseKATTs solution using a hashmap instead of an array.
This allows me to have a nice JSON object I can just for-in over in order to build my query filter.
http://plnkr.co/edit/CArP3Lkmn7T5PEPdXgNt?p=preview
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#*" data-semver="1.3.0" src="//code.angularjs.org/1.3.0/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
<style>
div{ margin: 1em;}
input{margin-left:1em;}
</style>
</head>
<body ng-controller="myCtrl">
<h2>Using a filter map tied to ng-model to create a filter object</h2>
<div ng-repeat="field in fields">
{{field}}<input ng-model=filters[field] />
</div>
<hr>
<h3>Filter</h3>
{{filters}}
<script>
var app=angular.module("app",[]);
app.controller("myCtrl",function($scope){
$scope.filters={};
$scope.fields=["name","address","phone","state"];
});
angular.bootstrap(document,["app"]);
</script>
</body>
</html>

Edit functionality in ng-controller

I am trying to display a list of objects from a controller and then trying to edit them.
I am binding data called editContact to value in input text box. I want to set a variable ii in scope and then when editing is done, then replace contacts[ii] with the temporary object editContact. But ii is not being recognized. Can I set a variable like ii?
<!doctype html>
<html ng-app>
<head>
<style>
</style>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
</head>
<body>
<div ng-controller="contactsController">
<label>Name</label>
<input ng-model="name" type="text" placeholder="Name">
<label>email</label>
<input ng-model="email" type="text" placeholder="Email">
<button ng-click="addContact()">Add contact</button>
<div>{{contactsController.name}}</div>
<div>
<ul>
<li ng-repeat="contact in contacts">
<div>{{contact.name}}</div>
<div>{{contact.email}}</div>
<div><button ng-click="deleteContact($index)">delete</button></div>
<div><button ng-click="editContact($index)">Edit</button></div>
</li>
</ul>
<input type="text" value="{{editContact.name}}"/>
<input type="text" value="{{editContact.email}}"/>
<button ng-click="changeValue(ii)">Edit</button>
</div>
</div>
<script>
// Your code goes here.
// $( document ).ready(function() {
// alert('jQuery asdfas!');
// Your code here.
// });
function contactsController($scope){
$scope.contacts=[{name:'asdf',email:'asdf'},
{name:'yweuir',email:'xcvzx'}
];
contactsController.prototype.addContact =function(){
console.log(this.name);
console.log(this.email);
this.contacts.push({name:this.name,email:this.email});
}
$scope.changeValue=function(){
$scope.contacts[$scope.ii]=$scope.editContact;
}
$scope.editContact=function(i){
$scope.editContact=$scope.contacts[i]
$scope.ii=i;
}
}
</script>
</body>
</html>
First, in the DOM always bind attributes for input boxes with ngModel. Example:
<input type="text" ng-model="editContact.name"/>
Second, never use $index as a point of reference for finding things in your controller. You should use the object itself. Example:
<li ng-repeat="contact in contacts">
<button ng-click="editSomeContact(contact)"></button>
</li>
Then your JavaScript should look like this:
$scope.addContact = function() {
$scope.contacts.push({name: '', email: ''});
};
$scope.editSomeContact = function(contact) {
$scope.editContact = contact;
};
$scope.deleteContact = function(contact) {
var index = $scope.contacts.indexOf(contact);
if(index > -1) {
$scope.contacts.splice(index, 1);
}
if($scope.editContact === contact){
$scope.editContact = null;
}
};
At this point, you don't need a changeValue function because you'll see that the contacts in the list will update with the edited fields due to the fact that the values are dynamically bound in both places.

Angularjs action on click of button

I am trying to do some calculation but it is getting done as soon as I enter the amount. I just want this to happen on click of a button rather than automatically.
What I have done so far:
<!DOCTYPE html>
<html ng-app="myAppModule">
<head>
<title>Angular JS - programming-free.com</title>
<link href="https://dl.dropbox.com/u/96099766/DetailModalExample/bootstrap.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="lib/angularjs.min.js"></script>
</head>
<body>
<div ng-controller="myAppController" style="text-align:center">
<p style="font-size:28px;">
Enter Quantity:
<input type="text" ng-model="quantity"/>
</p>
<h2>Total Cost: Rs.{{calculateval(quantity,10)}}</h2>
</div>
<script type="text/javascript">
var myAppModule = angular.module('myAppModule', []);
myAppModule.controller('myAppController', function($scope,calculateService) {
$scope.quantity=1;
$scope.calculateval = function(xval,yval) {
return calculateService.calculate(xval,yval);
}
});
// Service
myAppModule.factory('calculateService', function(){
return {
calculate: function(xval,yval){
return xval*yval;
}
}
});
</script>
</body>
</html>
The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity changes.
Instead you could try the following approach. Change your markup to the following:
<div ng-controller="myAppController" style="text-align:center">
<p style="font-size:28px;">Enter Quantity:
<input type="text" ng-model="quantity"/>
</p>
<button ng-click="calculateQuantity()">Calculate</button>
<h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>
Next, update your controller:
myAppModule.controller('myAppController', function($scope,calculateService) {
$scope.quantity=1;
$scope.quantityResult = 0;
$scope.calculateQuantity = function() {
$scope.quantityResult = calculateService.calculate($scope.quantity, 10);
};
});
Here's a JSBin example that demonstrates the above approach.
The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity changes.
This would involve updating the template to add an ng-change on the input, and an ng-if on the result:
<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>
and
<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>
In the controller add:
$scope.showQuantityResult = false;
$scope.calculateQuantity = function() {
$scope.quantityResult = calculateService.calculate($scope.quantity, 10);
$scope.showQuantityResult = true;
};
$scope.hideQuantityResult = function() {
$scope.showQuantityResult = false;
};
These updates can be seen in this JSBin demo.

Resources