I have an HTML form with the following fields: Note Type (as a combobox), Note Author: (as a textbox), and Note Description (as a textarea). This HTML form is written inside an AngularJS service in a variable and then displayed.
On click of the Save Note button, I need this information to be sent to a JSON array stored in another JavaScript file, which in turn, is displayed on a table as a list of notes.
The JSON array must be in the following form after say, two notes are added:
var noteData = [
{
"NoteType": "Type1",
"NoteAuthor": "John Doe",
"NoteDescription": "My first note."
},
{
"NoteType": "Type2",
"NoteAuthor": "Peter Doe",
"NoteDescription": "My second note."
} ];
How do I go about doing this?
My HTML form inside the AngularJS service looks like this:
var addNoteSection = '<label>Note Type: </label><br />' +
'<select ng-model="myModel.NoteType"><option value="Type 1">Type 1</option><option value="Type 2">Type 2</option>' +
'<label>Note Author: </label><br /><input type="text" ng-model="myModel.NoteCreator" /><br />' +
'<label>Note Description: </label><br /><textarea ng-model="myModel.NoteDescription" rows="4" cols="50"></textarea><br />' +
'<button ng-click="saveNewNote()">Save Note</button>'
try this.
var app = angular.module("app",[]);
app.controller("MyCtrl" , function($scope){
$scope.noteData=[];
$scope.myModel = {
"NoteType": "",
"NoteCreator":"",
"NoteDescription":""
};
$scope.saveNewNote = function(model){
var item = {
"NoteType": model.NoteType,
"NoteCreator": model.NoteCreator,
"NoteDescription": model.NoteDescription
};
$scope.noteData.push(item);
console.log($scope.noteData);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MyCtrl">
<label>Note Type: </label><br />
<select ng-model="myModel.NoteType">
<option value="Type 1">Type 1</option>
<option value="Type 2">Type2</option>
</select>
<label>Note Author: </label><br />
<input type="text" ng-model="myModel.NoteCreator" /><br />
<label>Note Description: </label><br />
<textarea ng-model="myModel.NoteDescription" rows="4" cols="50"></textarea><br />
<button ng-click="saveNewNote(myModel)">Save Note</button>
</div>
$scope.saveNewNote = function() { noteData.push($scope.myModel); }
Related
I'm trying to submit only the user modified data in an Angular Js form. How do we do it in Angular Js? (Version: 1.4.14).
I've come across the property $$success.parse of form. But there is no details about this property in Angular Js website. Can we use this property? Any help is appreciated.
As stated in comments, you want to check $dirty property of each form element.
See example here https://next.plnkr.co/edit/YW7ad8vYjfE9jnLW?preview
HTML
<body ng-controller="MainCtrl" ng-cloak>
<form name="userForm">
<div>
Name:
<input
name="name"
type="text"
ng-model="user.name"
ng-change="getChanges(userForm)">
Age:
<input
name="age"
type="number"
ng-model="user.age"
ng-change="getChanges(userForm)">
Gender:
<select
name="gender"
ng-model="user.gender"
ng-change="getChanges(userForm)">
<option value="M">M</option>
<option value="F">F</option>
<option value="O">Other</option>
</select>
</div>
<div>
<button
name="reset"
type="button"
ng-click="setPristine(userForm)">Set pristine
</button>
</div>
</form>
<div>
User changed values: {{ changedValues | json }}
</div>
</body>
JavaScript
angular.module('app', []).controller('MainCtrl', function($scope, $timeout) {
angular.extend($scope, {
user: {
name: null,
age: null,
gender: null
},
changedValues: {},
getChanges: function(form) {
$scope.changedValues = {};
angular.forEach(form, function(value, key) {
if (!key.startsWith('$')) {
if (value.$dirty) {
$scope.changedValues[key] = value.$modelValue;
}
}
});
},
setPristine: function(form) {
form.$setPristine();
$scope.getChanges(form);
}
});
$timeout($scope.reset);
});
This code works fine and outputs what I want to get but now I want to save each string or entry in an array so my entered data will not be lost. In this case, it is just working for one item I want to add multiple items and want to store them.
HTML code
<script src="angular.min.js"></script>
<script src="second.js"></script>
<link rel="stylesheet" type="text/css" href="bootstrap.min.css" />
<html ng-app="first">
<body ng-controller="second">
<form >
Enter YOur Name <input type="text" ng-model="product.name" placeholder="Enter Your Name" required><br>
Enter Your email <input type="email" ng-model="product.email" placeholder="Enter Your Email" required><br>
enter your pass<input type="password" ng-model="product.pass" placeholder="*******" required><br>
Enter Your Color <input type="radio" ng-model="product.radio" value="red" required><br>
select any of 1
<select ng-model="product.select">
<option>punjab</option>
<option>kpk</option>
<option>balochistan</option>
<option>peshawar</option>
</select>
<br>
<input type="submit" >
<input type="reset" >
</form>
{{product.name}}
{{product.email}}
{{product.pass}}
{{product.radio}}
{{product.select}}
</body>
</html>
js code
var app = angular.module("first", []);
app.controller("second", function($scope) {
$scope.product = [{
name: [],
email: [],
pass: [],
radio: [],
select: []
}];
});
I hope this is what you are looking for
Use a single array with multiple objects
On submitting the form your values shall be saved in the $scope.entrylist array
Controller function
function MainController($scope) {
$scope.color = {
name: 'none'
};
$scope.entrylist = [];
$scope.submit = function() {
var temp = {}
temp["name"] = $scope.product.name;
temp["email"] = $scope.product.email;
temp["password"] = $scope.product.pass;
temp["color"] = $scope.color.name;
temp["place"] = $scope.product.select;
$scope.entrylist.push(temp);
};
};
FULL EXAMPLE
I'm having large data of city names in .json file, i want to bind that all city names to my auto complete drop down list by using Mvc AngularJS so is there any way to do that,thanks in advance
https://github.com/ghiden/angucomplete-alt
You can make use of this plugin I think. Here's how you can use it.
<angucomplete-alt id="members"
placeholder="Search members"
pause="400"
selected-object="selectedCity"
remote-url="http://myserver.com/api/user/find?s="
remote-url-data-field="results"
title-field="name"
input-class="form-control form-control-small"/>
On server side you will receive the typed string as GET parameter.
Request.QueryString["type"];
Your server function should return the result in following JSON format.
{
results : [{'name': 'first city', 'name': 'second city'}]
}
2nd Option
In case you have to stick with static json file then you can use following approach as well. This will also work fast as all cities and loaded once and then filtering happens locally.
In Template
<div angucomplete-alt id="ex1"
placeholder="Search cities"
maxlength="50"
pause="100"
selected-object="selectedCity"
local-data="cities"
search-fields="name"
title-field="name"
minlength="1"
input-class="form-control form-control-small"
match-class="highlight">
</div>
then in your controller add this. This loads your json file into cities array which is used by the directive for auto complte purpose
$scope.cities = [];
$http.get('http://server/cities.json')..success(function(response) {
$scope.cities = response.data;
});
ng-options="color.Name for color in Colors"
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $window) {
$scope.Colors = [{
Id: 1,
Name: 'Red'
}, {
Id: 2,
Name: 'Blue'
}, {
Id: 3,
Name: 'Green'
}];
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<select ng-model="ddlColors" ng-options="color.Name for color in Colors track by color.Id">
</select>
</div>
Controller code
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $window) {
$scope.Fruits = [{
Id: 1,
Name: 'Apple'
}, {
Id: 2,
Name: 'Mango'
}, {
Id: 3,
Name: 'Orange'
}];
});
HTML Code
<label class="item item-input item-select">
<div class="input-label" style="color:#387ef5;">
Type of call :
</div>
<select name="fruitType" class="form-control" ng-change="getSectedTypeValue(selectedID)" ng-model="selectedID" ng-options=" fruitType as fruitType.Name for fruitType in Fruits track by fruitType.Id" value="{{fruitType.Id}}" required>
<option value=""> Select Call Type </option>
</select>
</label>
I'm trying to create a 'recipe' object that contains an array of 'ingredients' and their properties when a form is submitted. I created inputs with ng-models: recipe.name, recipe.servings, recipe.ingredients[0].name, recipe.ingredients[0].amount, recipe.ingredients[1].name, recipe.ingredients[1].amount, etc. But when the form is submitted, only recipe.ingredients[0]'s properties are recorded. In my controller, I have the following:
angular.module('recipeMavenApp')
.controller('AddRecipeCtrl', function () {
var vm = this;
vm.ingredientCount = 1;
vm.recipe = {
name: '',
servings: 0,
ingredients: [],
};
vm.appendIngredient = function() {
var newIngredientInput = angular.element('<input type="text"' +
'ng-model="recipe.ingredients[' + vm.ingredientCount + '].name" placeholder="Ingredient name" />' +
'<input type="number" min="0.25" max="1000" step="0.25" ng-model="recipe.ingredients[' +
vm.ingredientCount + '].amount" placeholder="Amount"/>');
angular.element(document.querySelector('#ingredients')).append(newIngredientInput);
vm.ingredientCount++;
};
vm.addRecipe = function(recipe) {
vm.recipe = recipe;
console.log(vm.recipe); //Testing to see what is received.
};
The form:
<form novalidate >
<div class="form-group">
<label for="recipeName">Name of Recipe</label>
<input type="text" ng-model="recipe.name" id="recipeName" required/>
</div>
<div class="form-group">
<label for="recipeServings">Number of Servings</label>
<input type="number" min="1" max="50" ng-model="recipe.servings" id="recipeServings"/>
</div>
<div class="form-group" id="ingredients">
<label for="recipeIngredients">Ingredients</label>
<button class="btn btn-primary btn-xs" ng-click="add.appendIngredient()">Add Ingredient</button>
<br />
<input type="text" ng-model="recipe.ingredients[0].name" id="recipeIngredients" placeholder="Ingredient name" />
<input type="number" min="0.25" max="1000" step="0.25" ng-model="recipe.ingredients[0].amount" placeholder="Amount"/>
<br/>
</div>
<button ng-click="add.addRecipe(recipe)" class="btn btn-primary"><span class="glyphicon glyphicon-share"></span> Add Recipe</button>
</form>
How do I capture all ingredients in the recipe.ingredients array on form submit?
I tried to rewrite your code there : JSFiddle
I used ng-repeat to generate the list of ingredients (where I uses the $index for the models) to avoid any DOM manipulation in the controller :
<div ng-repeat="ingredient in recipe.ingredients">
<input type="text" ng-model="recipe.ingredients[$index].name" placeholder="Ingredient name" />
<input type="number" min="0.25" max="1000" step="0.25" ng-model="recipe.ingredients[$index].amount" placeholder="0"/>
</div>
Based on the model :
$scope.recipe = {
name: '',
servings: 0,
ingredients: [{
name: '',
amount: null
}]
};
In the $scope.recipe.ingredients you can add how many {name:'', amount:null} as you need to show by default (you can also add a prefilled name or amount, for instance : {name:'Ingredient 1', amount:5}).
Then when I need a new ingredient I just push a new object in the $scope.ingredients array :
$scope.appendIngredient = function() {
$scope.recipe.ingredients.push({
name: '',
amount: null
});
};
Feel free to let me know if it fulfills your requirements or if you have any question.
Thanks
I have this model:
var Contact = Backbone.Model.extend({
defaults: function () {
return {
idc: ""
name: ""
email: "",
phones: new Array()
}
},
urlRoot: 'admin/contact'
});
This form (underscore template):
<form>
<input type="hidden" value="{{ idc }}" />
<p>
<label>Name:</label>
<input type="text" name="name" value="{{ name}}" />
</p>
<p>
<label>Email:</label>
<input type="text" name="email" value="{{ email }}" />
</p>
<p>
<label>Phones:</label>
<input type="text" name="phones[]" value="" />
<input type="text" name="phones[]" value="" />
<input type="text" name="phones[]" value="" />
</p>
<button class="cancel">Cancel</button><button class="save">Save</button>
</form>
And when I click in save, this function into Contact View:
e.preventDefault();
var formData = {},
prev = this.model.previousAttributes();
$(e.target).closest("form").find(":input").each(function () {
var el = $(this);
formData[el.attr("name")] = el.val();
});
this.model.set(formData);
this.model.save();
this.render();
I expect that when the function is called, it creates an array to send for the PHP file with the phones, so I can store it in the database. But looking at the browser console the attribute array is with the value: []
Is there something I´m missing to pass it to the PHP file?
PS: The array is in the formData array, but when I call this.model.save() looks like it lost the array.
Anyway, Thankyou!
Your problem is basically that you're using jQuery's serializeArray. serializeArray is great if you want to create a model for every form element, because it produces JSON like this (example JSON taken from the jQuery documentation):
[
{name: 'firstname', value: 'Hello'},
{name: 'lastname', value: 'World'},
{name: 'alias'}, // this one was empty
]
However, you don't want that, you want to create a single model from the combined elements; in other words you want:
{
firstname: 'Hello',
lastname: 'World',
alias: undefined
}
There are jQuery plug-ins that produce output like that if you want, but personally I'd recommend just writing your own. If you have a form view with an onSubmit handler, you could do something like:
this.model.set('name', this.$('[name="name"]').val());
this.model.set('email', this.$('[name="email"]').val());
// etc.
that's tailored specifically for your app and serializes the data the exact way you want.