Angular JS binding scope data within ng-repeat to form - angularjs

I have a collection of items in $scope.data with fields "id","name" & "age", that are being displayed in the view using ng-repeat directive.
For each set of items, there is a corresponding "edit button".
I want to be able to access values for the particular set of items for which edit button was pressed.
Html:
<div ng-controller="Ctrl">
<div ng-repeat="i in data">
Name: {{i.name}}
Age: {{i.age}}
<form ng-submit="submit()">
<input type="text" ng-model="i.id"/>
<input type="submit" value="Edit" />
</form>
</div>
</div>
Script:
function Ctrl($scope)
{
$scope.data = [
{id:1,name:"Alex",age:22},
{id:2,name:"Sam", age:28}
];
$scope.submit = function() {
//access id of user for which edit was clicked
};
}
What is the right way to do this?

Instead of a form, I would suggest you just use a button:
<div ng-controller="Ctrl">
<div ng-repeat="i in data">
Name: {{i.name}}
Age: {{i.age}}
<input type="text" ng-model="i.id"/>
<button ng-click="submit(i)">Edit</button>
</div>
</div>
Just send i into the button click event (I suppose you could use form if you need validation, but your example doesn't seem to need it).
Your submit function then changes to:
$scope.submit = function(selectedItem) {
// here you now have access to selected item
};

Try this:
HTML:
<form ng-submit="submit(i.id)">
JavaScript:
$scope.submit = function(userId) {
// you have userId
};

One option is to just use an ng-click within a button that calls your submit passing in i
<div ng-controller="Ctrl">
<div ng-repeat="i in data">
Name: {{i.name}}
Age: {{i.age}}
<button ng-click="submit(i);">edit</button>
</div>
</div>
and the function:
$scope.submit = function(i) {
console.log(i);
//access id of user for which edit was clicked
};
Here's a fiddle of that working: http://jsfiddle.net/pRAcP/

Related

Passing checkbox values to controller in Angular JS

I have a group of checkboxes which are populated from,the database. Each checkbox value contains a Book Id.
Now I have a Save button which contains a ng-click="save()" function. How can I pass the value of checked book Ids to the controller, and how can I catch the array of Ids in the controller' save() method. How can I bind the checkbox values, with the controller, here?
Here is the code in the view,
<div ng-repeat="bk in Books">
<input type="checkbox" value={{bk.Id}} ng-checked="$index ===0 ? true : false"/>{{bk.Name}}
</div>
<br/>
<input type="button" id="save" class="btn btn-success" value="Save" ng-click="save()"/>
<br/>
You don't need to pass the Ids values from the view, you can grab them directly within the controller through the binding mechanism.
Here you have a working sample. Whit this you can get rid of value={{bk.Id}} and ng-checked="$index ===0 ? true : false". Also notice how it is initialized the state (checked or unchecked) of the checkbox: ng-init="bookModel[bk.Id] = $first" which sets the checkbox checked only for the first element in the list.
angular
.module('app', [])
.controller('ctrl', function($scope) {
$scope.Books = [{
Id: 1,
Name: "Harry Potrer"
},
{
Id: 2,
Name: "Python"
},
{
Id: 3,
Name: "C#"
}
];
$scope.bookModel = {};
$scope.save = function() {
var checkedBooks = [];
for (var k in $scope.bookModel) {
if ($scope.bookModel.hasOwnProperty(k) && $scope.bookModel[k]) {
checkedBooks.push(k);
}
}
//do your stuff with the ids in `checkedBooks`
alert(checkedBooks);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<span ng-app="app" ng-controller="ctrl">
<div ng-repeat="bk in Books">
<input type="checkbox" ng-model="bookModel[bk.Id]" ng-init="bookModel[bk.Id] = $first"/>{{bk.Name}}
</div><br/>
<input type="button" id="save" class="btn btn-success" value="Save" ng-click="save()" />
</span>

Angular radio button listing with ng-repeat

How can i clear radio buttons checked status when click on 'clear' buttons ?
Listing radio buttons in ng-repeat,
<label ng-repeat="item in items">
<input type="radio" name="test" ng-model="test" value="{{item.name}}" />{{item.name}}
</label>
<a class="undo" ng-click="clear()">Clear</a>
fiddle
And is it possible clear checked status from another controller ?
This will works fine..!!!
angular.module("myApp", []).controller("Example", ["$scope", function($scope) {
$scope.data = {};
$scope.items = [
{name: 'one'},
{name: 'two'},
{name: 'three'},
{name: 'four'},
{name: 'five'},
];
$scope.clear = function(){
$scope.data = {};
//alert("hello");
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script>
<div ng-app="myApp" ng-controller="Example">
<label ng-repeat="item in items">
<input type="radio" name="test" ng-model="data.test" value="{{item.name}}" />{{item.name}}
</label>
<br>
<a class="undo" ng-click="clear()">Clear</a>
</div>
You can use a broadcast event. See this answer: https://stackoverflow.com/a/19498009/4161992
Then in your controller that controls your input radio, do this:
.controller('radioController', function($scope){
$scope.$on('triggerClearRadio', function(){
$scope.items.forEach(function (item, i) {
item.checked = false;
});
});
});
Change your input html to use ng-model="item.checked" instead of ng-model="test"
From your clear button you can broadcast the 'triggerClearRadio' event (name it something better though) like this:
<button type="button" ng-click="$root.$broadcast('triggerClearRadio')>Clear radios</button>
See this fiddle: http://jsfiddle.net/takuan/aaoub2mg/

how to remove the value of an input field using angularjs

<div class="info-block" ng-app="">
<div ng-controller="Note">
<div class="checkbox">
<label>
<p><b>Primary Publication: </b>
{{ form_widget(form.input_ppubs, { 'attr': {'class': 'valOption'}}) }}
</p>
</label>
</div>
<div ng-repeat="item in items">
<input type="text" placeholder="new input" ng-model="item.primaryPub">
</div>
<button type="button" ng-click="add()">New Item</button>
</div>
I am trying to retrieve the value of the html input field and remove it from input upon a button click
I am able to get the code, but I don't know how to remove the code.
var Note = function($scope){
$scope.items = [];
$scope.add = function () {
//angular way of implementing document.getElementByID();
pub1 = angular.element('#form_input_ppubs').val();
$scope.items.push({
primaryPub: pub1
});
};
}
You don't have to retrieve your items like this. It's ugly and not the angular way. angular.element('#form_input_ppubs').val();
Instead, simply reference it in your input using ngModel.
Declare it in your scope.
$scope.inputItem = null;
HTML
<input ng-model="inputItem " />
Use it in your function:
$scope.addItem = function(item) {
$scope.items.push(item);
//reset the model
$scope.inputItem = null;
}
Call it using ng-click
<button type="button" ng-click="addItem(inputItem)">Add Item</button>
If you do:
console.log($scope.items);
You should see an entry for primaryPub, the model for your input. Then you can target it by nulling the model, so:
$scope.items.primaryPub = null;
However you're using this inside an ng-repeat:
<div ng-repeat="(i, item) in items">
<input type="text" placeholder="new input" ng-model="items[i].primaryPub">
</div>
So your console.log (if you have more than one item in 'items') should show an array-like structure for primaryPub.

Angular js Dynamic Input and show value

I want dynamic input in my form so that user can add many input as much he wants
Same time I want to display the value of it..
Example:
Suppose i have one input
Customer: <input type="text" ng-model="name"/> <!--first input>
<a>Add more</a>
I can easily get value for it
All customers <p ng-bind="name"></p>
BUT if users add one more customer name input, Then how can i show that value
Under "All customers tag"
All customers <p ng-bind="name"></p> // Customer1,Customer1 name here
Use an array of objects on scope in conjunction with a ng-repeat. The button will then add to the array.
View:
<p ng-repeat="item in array">Name: <input type="text" ng-model="item.name" ></p>
<button ng-click="add()">Add</button>
<p>All customers</p>
<p ng-repeat="item in array">{{item.name}}</p>
Js:
app.controller('MainCtrl', function($scope) {
$scope.array = [];
$scope.add = function () {
$scope.array.push({ name: ''});
}
$scope.add();
});
Plunkr
You have to create array.
In your controller
$scope.inputs = [];
$scope.add = function() {
$scope.inputs.push({value: ''});
}
$scope.add();
now in HTML
<div ng-repeat="input in inputs">
<input type="text" ng-model="input.value" />
</div>
<button ng-click="add()">Add</button>
This is raw concept of how that might be done.
Update
Added plunker example
http://plnkr.co/edit/bHLXCjsP46GiixysZZ83?p=preview

Bind dynamic element creation to keypress with AngularJS

I am trying to append an element to the DOM from user text input using AngularJS.
The desired behaviour is:
User types string into input ng-model "newTask"
Presses enter key
Dynamic element is then appended to the DOM
The relevant section of HTML is as follows:
<div class="add-task">
<input type="text" placeholder="Type then press enter to create task" ng-model="newTask" />
</div>
<div class="task-list">
<a class="task"><span class="text">{{ newTask }}</span></a>
</div>
Currently the HTML is instantly updated. How can I bind this event to only happen after enter keypress? The AngularJS UI is also loaded.
Many appreciations,
an AngularJS newbie
Try creating a temp value
Html:
<input type="text" placeholder="Type then press enter to create task" ng-model="tmpTask" ng-keypress="saveTask($event)" />
Your ng-model binds to a tmpTask property. Only when enter is pressed, save it back to newTask
JS:
app.controller('MainCtrl', function($scope) {
$scope.saveTask = function (event){
if (event.keyCode == 13){
$scope.newTask = $scope.tmpTask;
}
}
});
DEMO
html
<form ng-submit="createTask()">
<input type="text" ng-model="newTaskText" />
</form>
<div ng-repeat="task in tasks">{{ task.text }}</div>
controller
$scope.tasks = [];
$scope.createTask = function() {
$scope.tasks.push({
text: $scope.newTaskText
});
};
Since one of the other answers addresses the ng-keypress, I'll offer up the fact you don't need to use the ng-keypress event but can just watch the variable instead which negates the need for enter:
http://plnkr.co/edit/osFGRtpHG46bMyp15mc8?p=preview
app.controller('MainCtrl', function($scope) {
$scope.taskList = [];
$scope.$watch('newTask', function(newVal){
if (newVal=="newTask") {
$scope.taskList.push("Task " + $scope.taskList.length);
$scope.newTask = null;
}
});
});
<body ng-controller="MainCtrl">
<div class="add-task">
<input type="text" placeholder="Type then press enter to create task" ng-model="newTask" />
</div>
{{taskList.length}}
<div class="task-list" >
<a class="task" ng-repeat="task in taskList" ><span class="text">{{ task }} </span></a>
</div>
</body>

Resources