Creating editable child from parent Angular data - javascript

Is there a native way to do something like this in Angular? I know of ng-repeat, but not sure how to implement it in this instance.
Basically, it would duplicate Id Number with an increased number e.g, 1001, 1002, etc and be able to create a new Name.
So:
Id Number: 1000
Bob
Id Number: 1001
Sue
Id Number: 1002
Rumplestiltskin
Form Data:
<body ng-controller="MainCtrl">
Enter Name:
<input type="text" ng-model="name">
<br />
<div id="data">
Id Number: {{num}}
<br />Name: {{name}}
</div>
<form ng-submit=incNum()>
<input class="btn btn-primary" type="submit" value="New User">
</form>
</body>
Controller:
app.controller('MainCtrl', function($scope) {
$scope.num = 1000;
$scope.incNum = function ()
{
$scope.num ++;
$scope.data.clone();
}
});
Plunker Demo

Totally. This is where Angular shines. Just add an object into an array and let ng-repeat do the work. Try this out.
HTML
Enter Name: <input type ="text" ng-model="name"> <br />
<div id="data">
Id Number: {{num}}<br />
Name: {{name}}
</div>
<form ng-submit=addUser()>
<input class="btn btn-primary" type="submit" value="New User">
</form>
<div ng-repeat="user in users">{{user.name}}: {{user.id}}</div>
Javascript
$scope.num = 1000;
$scope.users = [];
$scope.addUser = function () {
$scope.num++;
$scope.users.push({
name: $scope.name,
id: $scope.num
});
}

Related

Angularjs: input for ng-repeat elements

Sorry for my language skills, hope you understand all.
I need to make inputs for ng-repeat elements, to pass input data to http post.
For example: i have 4 elements, for all elements i make inputs, and f.e:
elem1- input: 1
elem2- input: 4
elem3- input: 1
elem4- input: 2
Here is my code:
.panel-body.note-link ng-repeat=("meal in mealsList track by $index")
a data-toggle="tab"
h4.pull-right.text-muted
| {{meal.price}} zł
h4.text-success
i.fa.fa-close.text-danger<> ng-click="removeMeal($index)" style="cursor: pointer;font-size: 15px;"
| {{meal.name}} {{$index}}
input.form-control type="number" ng-model="example"
| {{example}}
And i dont know, how to pass input data to controller.
Any tips,tricks?
angular.module('yourModule').controller('viewController', function($scope) {
$scope.mealList = [...];
$scope.example; //The input data will automatically bind to this variable.
});
If you want the input to change data within your meal object, then do this:
input.form-control type="number" ng-model="meal.example"
And then the property value of the meal object would bind to the input
Repeat through your mealList array and add the inputs.
Example: https://jsfiddle.net/ptzhL0uL/
Controller
function Controller1($scope) {
var vm = this;
vm.items_saved = false;
vm.mealList = [{
price: '2.99',
name: 'Pizza'
}, {
price: '1.99',
name: 'Chips'
}, {
price: '4.99',
name: 'Beer'
}];
vm.addNewItem = addNewItem;
vm.saveItems = saveItems;
function addNewItem() {
vm.mealList.push({});
}
function saveItems() {
vm.items_saved = true;
}
}
HTML
<button ng-click="ctrl.addNewItem()" class="btn btn-default">Add Item</button>
<div ng-repeat="item in ctrl.mealList">
<input type="text" ng-model="item.name">
<input type="text" ng-model="item.price">
<input type="number" ng-model="item.quantity">
</div>
<button ng-click="ctrl.saveItems()" class="btn btn-primary">Save</button>
<hr>
<div ng-if="ctrl.items_saved">
<h4>Here is your meal list:</h4>
<ul>
<li ng-repeat="item in ctrl.mealList">{{item.quantity}}{{item.name}} at ${{item.price}} each</li>
</ul>
</div>
Just attach it to the ngModel directive.
<div ng-repeat="item in array">
{{ item.output }}
<input ng-model="item.output" />
</div>

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

I need to generate form input fields dynamically by clicking 'add sale' button on the form. which is accomplished
Also on change selected drop down, it get the price from the database and use the quantity to calculate the amount of that product.
if I click on 'add sale' button for another form generate the changes affect the previous one.
how to calculate the amount for each form independently and collect the data in it using angularJS?
this is controller
appcat.controller("MainCtrl", ['$scope', '$http', '$location', function ($scope, $http, $location)
{
//var quan = $scope.quantity;
$http.get('/api/pproduct').success(function (data)
{
$scope.pcategoryA = data;
});
// this controll the addition and removal
$scope.choices = [{ id: 'choice1' }];
//any time changes occurr it calculate the Amount
$scope.changedValue = function (item,quan)
{
if (item != null && quan !=null)
{
$http.get('/api/product/'+ item).success(function (data) // this is the price for that product from the Database
{
//this sets amount field
$scope.amount = parseFloat(data.price * quan);
});
}
}
// this generate a form
$scope.addNewChoice = function ()
{
var newItemNo = $scope.choices.length + 1;
$scope.choices.push({ 'id': 'choice' + newItemNo });
};
// this remove the form
$scope.removeChoice = function () {
var lastItem = $scope.choices.length - 1;
if ($scope.choices.length > 1) {
$scope.choices.splice(lastItem);
}
};
}]);
this is the html
<form class="form-inline" role="form" padding-left:10em">
<strong class="error">{{ error }}</strong>
<div class="form-group">
<label for="name">
Invoice No. :
</label>
<input type="text" class="form-control" id="name" ng-model="name" />
</div>
<br /><hr />
<div ng-controller="MainCtrl">
<fieldset data-ng-repeat="choice in choices">
<div class="form-group">
<label for="name">
Quantity :
</label>
<input type="text" class="form-control" id="quantity" ng-model="quantity" />
</div>
<div class="form-group">
<div class="form-group">
<label class="control-label"> Product : </label>
<select class="form-control" id="selected_id" ng-model="selected_id" ng-options="c.Value as c.Text for c in pcategoryA"
ng-change="changedValue(selected_id,quantity)">
<option value="">-- Select Category --</option>
</select>
</div>
</div>
<div class="form-group">
<label for="name">
Amount :
</label>
<input type="text" class="form-control" id="amount" ng-model="amount" ng-readonly="true" />
</div>
<button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>
<br />
<hr />
</fieldset>
<button type="submit" class="col-sm-offset-10 addfields" ng-click="addNewChoice()">
Add Sale
</button>
</div>
</form>
thanks in advanced!!
You have to put 'amount' in choices array.
$scope.choices = [{ id: 'choice1', amount: 0}];
Then in controller:
$scope.changedValue = function (choise,item,quan)
choise.amount = parseFloat(data.price * quan);
And in tempalte:
ng-change="changedValue(choise,selected_id,quantity)">
<input type="text" class="form-control" id="amount" ng-model="choise.amount" ng-readonly="true" />

Angularjs $setPristine not working with controller as syntax

$setPristine works alright when referenced with $scope but doesn't seem to work with 'controller as syntax'
In View:
<h2>With Controller as syntax</h2>
<div ng-controller="FirstCtrl as first">
<form name="form1" id="form" novalidate>
<input name="name" ng-model="first.data.name" placeholder="Name" required/>
<button class="button" ng-click="first.reset()">Reset</button>
</form>
<p>Pristine: {{form1.$pristine}}</p>
<p> <pre>Errors: {{form.$error | json}}</pre> </p>
</div>
<hr>
<h2>With $scope</h2>
<div ng-controller="SecondCtrl">
<form name="form1" id="form" novalidate>
<input name="name" ng-model="data.name" placeholder="Name" required/>
<button class="button" ng-click="reset()">Reset</button>
</form>
<p>Pristine: {{form1.$pristine}}</p>
<p> <pre>Errors: {{form.$error | json}}</pre> </p>
</div>
In app.js:
var app = angular.module('plunker', []);
app.controller('FirstCtrl', function() {
'use strict';
var vm = this;
vm.data = { "name": ""};
vm.reset = function() {
vm.data.name = "";
vm.form1.$setPristine();
}
});
app.controller('SecondCtrl', function($scope) {
'use strict';
$scope.data = { "name": ""};
$scope.reset = function() {
$scope.data.name = "";
$scope.form1.$setPristine();
}
});
Here is the plunker: http://plnkr.co/edit/VcgZx3?p=preview
Even if you use controller as syntax, the form and other attributes are still bound to the scope not to the controller instance so you still have to use $scope.form1.$setPristine(); to set the form's state.
var app = angular.module('my-app', [], function() {})
app.controller('FirstCtrl', function($scope) {
'use strict';
var vm = this;
vm.data = {
"name": ""
};
vm.reset = function() {
vm.data.name = "";
$scope.form1.$setPristine();
}
});
app.controller('SecondCtrl', function($scope) {
'use strict';
$scope.data = {
"name": ""
};
$scope.reset = function() {
$scope.data.name = "";
$scope.form1.$setPristine();
}
});
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
<div ng-app="my-app">
<h2>With Controller as syntax</h2>
<div ng-controller="FirstCtrl as first">
<form name="form1" id="form" novalidate>
<input name="name" ng-model="first.data.name" placeholder="Name" required/>
<button class="button" ng-click="first.reset()">Reset</button>
</form>
<p>Pristine: {{form1.$pristine}}</p>
<p> <pre>Errors: {{form.$error | json}}</pre> </p>
</div>
<hr/>
<h2>With $scope</h2>
<div ng-controller="SecondCtrl">
<form name="form1" id="form" novalidate>
<input name="name" ng-model="data.name" placeholder="Name" required/>
<button class="button" ng-click="reset()">Reset</button>
</form>
<p>Pristine: {{form1.$pristine}}</p>
<p> <pre>Errors: {{form.$error | json}}</pre> </p>
</div>
</div>
An alternative to using Arun's suggestion of accessing the form through $scope is simply to ensure the form is accessible through the controller.
To do this all you have to do is change your HTML for the 'controller as' version very slightly. Change the form's name to include the controller object, also change any references to the form from the template to include the controller variable:
<h2>With Controller as syntax</h2>
<div ng-controller="FirstCtrl as first">
<form name="first.form1" id="form" novalidate>
<input name="name" ng-model="first.data.name" placeholder="Name" required/>
<button class="button" ng-click="first.reset()">Reset</button>
</form>
<p>Pristine: {{first.form1.$pristine}}</p>
<p> <pre>Errors: {{form.$error | json}}</pre> </p>
</div>
<hr>
Your Javascript will now run unchanged.
I think an even easier way to accomplish this is to provide the form controller as a parameter to the reset() function:
…
<button class="button" ng-click="reset(form1)">Reset</button>
…
and change the reset() function slightly, so that it uses the supplied parameter:
$scope.reset = function(form) {
$scope.data.name = "";
form.$setPristine();
}
You can use $setPristine without $scope:
<form ng-submit="$ctrl.save()" name="$ctrl.myForm">
And in your controller:
var $ctrl = this;
...
$ctrl.myForm.$setPristine();
$ctrl.myForm.$setUntouched();
It works for me. (AngularJS v1.5.7)

How can I get a value from a form and use it in a controller?

My code: http://pastebin.com/AyFjjLbW
I'm trying to learn AngularJS and in the beginning it was going well but now I am stuck. What I want to do is use the drop down menu to select a priority and a type of job that can be done but I can not figure out how on earth I can get a value from a input tag and use it in my script when I try to push a value from an array into my object.
You can see my failed attempt here:
priority: $scope.priority[other_options.worktype]
Thank you!
Here is the proper way of doing what you want :
<!DOCTYPE html>
<html lang="en-us" ng-app="todoApp">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<head>
<title>Alex's Todo List</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<div ng-controller="placingItems">
<h1>To Do List</h1>
<center><button type="button" ng-click = "clear_all()">Clear List</button></center>
<p>What to do: <input type="text" ng-model="thing">
<form name="other_options">
<select ng-model="worktype" ng-options="worktype.label for worktype in worktypeList" ></select>
<select ng-model="priority" ng-options="priority.label for priority in priorityList" ></select>
<input type="submit" ng-click="add()">
</form>
</p>
<div class="block">
<p>To do:</p>
<center><li ng-repeat = "x in items">
<span ng-style="cmplt">{{ x.name }}</span> {{ x.type.label }} {{ x.priority.label }}
<button type="button" ng-click="cmplt={color: 'gray', 'text-decoration': 'line-through'}">Completed</button>
</li></center>
</div>
</div>
</body>
</html>
<script>
angular.module('todoApp.controllers', [])
.controller('placingItems', ['$scope', function($scope) {
$scope.thing = "Nothing";
$scope.items = [];
$scope.priorityList = [{
label:'Top Priority',
id: 1
}, {
label: 'Mid Priority',
id: 2
}, {
label: 'Low Priority',
id: 3
}];
$scope.worktypeList = [{
label:'Work',
id: 1
}, {
label: 'Personal',
id: 2
}];
$scope.add = function(){
$scope.items.push({
name: $scope.thing,
priority: $scope.priority,
type: $scope.worktype
});
};
$scope.clear_all = function(){
$scope.items = [];
};
}]);
var app = angular.module('todoApp', ['todoApp.controllers']);
</script>
Your form field should have ng-model associated with them so that you can access those value inside controller scope. Basically when your create a form with name attribute, at that time name attribute gets added to controller scope variable & then that scope variable will give you all the form related validation inside the object.
Markup
<form name="other_options" ng-init="formData={}">
<select name="worktype" ng-model="formData.worktype">
<option selected value="-" name = "work">Work</option>
<option value="1" name="home">Home</option>
</select>
<select name="priortype" ng-model="formData.worktype">
<option value="0" name="top">Top Priority</option>
<option selected value="1" name="mid">Mid Priority</option>
<option value="2" name="low">Low Priority</option>
</select>
<input type="submit" ng-click="add()">
</form>
Then only you can access this value inside controller using like $scope.formData.worktype
Code
$scope.add = function(){
$scope.items.push(
{name: $scope.thing,
priority: $scope.formData.worktype, //or $scope.formData["worktype"]
type: $scope.type[1]
});
};
Take a look at http://www.quora.com/How-do-I-get-HTML-form-input-value-in-AngularJs-controller it is very good. Hope this is what you need.

ng-click does nothing (todo list example)

I try to play around with some test in angular. but failed to add item in a todo list app sample:
app.controller('MainControl', function($scope){
$scope.tasks = [
{
"name":"task 1",
},
{"name":"task 2",
}
];
var addTask = function(){
$scope.tasks.push({
"name": $scope.input,
});
$scope.input = "";
};
});
I wonder why it doesn't work, no error in the console.
my html
<body ng-controller="MainControl">
<div>
<label>I want to:</label>
<input type="text" ng-model="input">
<button ng-click="addTask()">Add</button>
</div>
<div>
<ul ng-repeat="task in tasks">
<li>{{task.name}}</li>
</ul>
</div>
</body>
addTask must be a $scope property, i.e. $scope.addTask = function() {} instead of var addTask = function() {}.
Edit after comments:
<form ng-submit="addTask()">
<label>I want to:</label>
<input type="text" ng-model="input">
<button type="submit">Add</button>
</form>

Categories