Reflecting data from JSON path to table using Angular JS - angularjs

To add the JSON data to Table by using Angular JS.
https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js">
Filter
Ascending Order
Descending Order
USER ID
ID
TITLE
COMPLETED
ACTION
<tbody>
<tr ng-repeat="x in userId">
<td>
<div ng-hide="editingData[x.id]">{{x.userId}} </div>
<div ng-show="editingData[x.id]"><input type="text" ng-model="x.userId" /></div>
</td>
<td>
<div>{{x.id}}</div>
</td>
<td>
<div ng-hide="editingData[x.id]">{{x.title}} </div>
<div ng-show="editingData[x.id]"><input type="text" ng-model="x.title" /></div>
</td>
<td>
<div ng-hide="editingData[x.id]">{{x.completed}} </div>
<div ng-show="editingData[x.id]"><input type="text" ng-model="x.completed" /></div>
</td>
<td>
<button ng-hide="editingData[x.id]" ng- click="modify(x)">Modify</button>
<button ng-show="editingData[x.id]" ng- click="update(x)">Update</button>
<button ng-hide="viewField">Remove</button>
</td>
</tr>
</tbody>
</table>
</div>
<div>
<div>ADD NEW DETALS</div>
<form class="form-horizontal" role="form" ng-submit="addRow()">
<div class="form-group">
<label class="col-md-2 control-label">USER ID</label>
<div class="col-md-4">
<input type="text" class="form-control" name="userId"
ng-model="x.userId" />
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">ID</label>
<div class="col-md-4">
<input type="text" value=201 class="form-control" name="id"
ng-model="x.id" />
</div> </div>
<div class="form-group">
<label class="col-md-2 control-label">TITLE</label>
<div class="col-md-4">
<input type="text" class="form-control" name="title"
ng-model="x.title" />
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">COMPLETED</label>
<div class="col-md-4">
<input type="text" class="form-control" name="completed"
ng-model="x.completed" />
</div>
</div>
<div class="form-group">
<div style="padding-left:110px">
<input type="submit" value="Submit" class="btn btn-primary"/>
</div>
</div>
</form>
</div>
</body>
</html>
Controllers.js
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$scope.userId = [];
$http.get("").success(function (response)
{$scope.userId = response});
$scope.editingData = [];
for (var i = 1, length = $scope.userId.length; i < length; i++) {
$scope.editingData[$scope.userId[i].id] = false;
}
$scope.modify = function(x){
$scope.editingData[x.id] = true;
};
$scope.update = function(x){
$scope.editingData[x.id] = false;
};
});
$scope.addRow =function( event ){
if (event.success) {
$http.post("", { 'userId':$scope.userId, 'id': $scope.id, 'title':$scope.title, 'completed':$scope.completed })
.success(function (response)
{$scope.userId = response;
});
}
}
Style.css
body {
background-color: #eef;
}
#tabs {
width: 95%;
margin-left: auto;
margin-right: auto;
margin-top: 10px;
}
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 4px;
font-family: arial;
}
td {
text-align: center;
}
th {
background: darkblue;
color: white;
text-align: center;
}
/*Style for Alternate Rows*/
table tr:nth-child(odd) {
background-color: #C2EBC3;
}
table tr:nth-child(even) {
background-color: #FFFFFF;
}
Simple example
<!DOCTYPE html>
<html>
<head>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body ng-app="MyApp">
<input type="text" ng-model="text" placeholder="Enter text"/>
<p>Input: {{ text }}</p>
<p>Filtered input: {{ text | reverse }}</p>
<my-directive></my-directive>
<script type="text/javascript">
app.angular.module('myApp', [])
.directive('myDirective', function() {
return {
restrict: 'E',
template: '<a href="http://google.com">
Click me to go to Google</a>'
}
});
var app = angular.module("MyApp", []);
app.filter("reverse", function() {
return function(input) {
var result = "";
input = input || "";
for (var i=0; i<input.length; i++) {
result = input.charAt(i) + result;
}
return result;
};
});
</script>
</body>
</html>
For reference you can use this links
"http://www.revillweb.com/tutorials/angularjs-in-30-minutes-angularjs-tutorial/"
"Push json data to existing array in angular js"
"Adding new row of fields with AngularJS ng-repeat"
"Angularjs - Update JSON"

You need to define your app only once. you need to remove this line var app = angular.module("MyApp"); which is flushing your app which has myDirective directive.
Code
app.angular.module('myApp', [])
.directive('myDirective', function() {
return {
restrict: 'E',
template: '<a href="http://google.com">
Click me to go to Google < /a>'
}
});
app.filter("reverse", function() {
return function(input) {
var result = "";
input = input || "";
for (var i = 0; i < input.length; i++) {
result = input.charAt(i) + result;
}
return result;
};
});

Related

Dynamic textbox validation using ng-repeat

I have following code which add dynamically textbox. The form contains Name and Programing skill textbox. The Programing skill textbox can be added dynamically.
I am trying to validate dynamic textbox. As of now it generates textbox every time when I click on "ADD" Button. If I entered anything in textbox then only it should be allowed to generate next textbox , else it should show a message/alert to fill the textbox.
I use ng-repeat to generate textbox.
<!DOCTYPE html>
<html>
<head>
<title>validation</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
</head>
<body>
<div ng-app="dynamicApp" ng-controller="dynamicController" class="container" style="width:600px;" ng-init="fetchData()">
<div class="alert alert-success alert-dismissible" ng-show="success" >
×
{{successMessage}}
</div>
<div class="alert alert-danger alert-dismissible" ng-show="error" >
×
{{errorMessage}}
</div>
<form method="post" ng-submit="submitForm()">
<div class="form-group">
<label>Enter Your Name</label>
<input type="text" name="name" id="name" ng-model="formData.person_name" class="form-control" />
</div>
<fieldset ng-repeat="row in rows">
<div class="form-group">
<label>Enter Your Programming Skill</label>
<div class="row">
<div class="col-md-9">
<input type="text" name="programming_languages[]" class="form-control" ng-model="formData.skill[$index + 1]" />
</div>
<div class="col-md-3">
<button type="button" name="remove" ng-model="row.remove" class="btn btn-danger btn-sm" ng-click="removeRow()"><span class="glyphicon glyphicon-minus"></span></button>
</div>
</div>
</div>
</fieldset>
<div class="form-group">
<button type="button" name="add_more" class="btn btn-success" ng-click="addRow()"><span class="glyphicon glyphicon-plus"></span> Add</button>
<input type="submit" name="submit" class="btn btn-info" value="Save" />
</div>
</form>
<div class="table-responsive">
<table class="table table-bordered table-striped">
<tr>
<th>Name</th>
<th>Programming Languages</th>
</tr>
<tr ng-repeat="name in namesData">
<td>{{name.name}}</td>
<td>{{name.programming_languages}}</td>
</tr>
</table>
</div>
</div>
</body>
</html>
<script>
var app = angular.module('dynamicApp', []);
app.controller('dynamicController', function($scope, $http){
$scope.success = false;
$scope.error = false;
$scope.fetchData = function(){
$http.get('/home/testdata').success(function(data){
$scope.namesData = data;
});
};
$scope.rows = [{name: 'programming_languages[]', name: 'remove'}];
$scope.addRow = function(){
var id = $scope.rows.length + 1;
$scope.rows.push({'id':'dynamic'+id});
};
$scope.removeRow = function(row){
var index = $scope.rows.indexOf(row);
$scope.rows.splice(index, 1);
};
$scope.formData = {};
$scope.submitForm = function(){
$http({
method:"POST",
url:"/home/test",
data:$scope.formData
}).success(function(data){
if(data.error != '')
{
$scope.success = false;
$scope.error = true;
$scope.errorMessage = data.error;
}
else
{
$scope.success = true;
$scope.error = false;
$scope.successMessage = data.message;
$scope.formData = {};
$scope.rows = [{name: 'programming_languages[]', name: 'remove'}];
$scope.fetchData();
}
});
};
});
</script>

ng-click expression not registrering

I have this small AngularJS app, and most ng-click expressions work fine.
As an example I use submitted=true and submitted=false as hide and show for some buttons and to add a class show to the ingredients div. However, I can't get ng-click="submitted=false" on the last button .restart to work? On this click it should make the expression submitted=false, so the ingredients div will not have the show class anymore, and change the buttons.
How come?
Fiddle
var app = angular.module("app", []);
app.controller("IndexController", ["$scope", function($scope) {
this.list = {
"mandag": {}
};
this.submitted = false;
this.addFood = (day, title) => {
this.list[day] = {
"food": title,
"ingredients": []
};
}
this.removeFood = (day) => {
this.list[day] = {};
}
this.addIngredient = (day, ingredient) => {
this.list[day].ingredients.push({
"name": ingredient.name,
"amount": ingredient.amount,
"unit": ingredient.unit
});
}
this.UnSave = () => {
this.list.mandag = {};
}
}]);
.shopping {
width: 25%;
}
.ingredients {
opacity: .1;
transition: opacity 1s ease;
}
.show {
opacity: 1;
}
button {
border: none;
background: transparent;
}
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="app" >
<div ng-controller="IndexController as vm">
<div style="margin: 20px; display: inline-block;" ng-repeat="(day, item) in vm.list track by $index" class="card-panel teal col s9">
<h3>{{day}}</h3>
<form class="" name="ret" ng-submit="vm.addFood(day, item.food)">
<input placeholder="" name="inputRet" class="inputRet" ng-disabled="submitted" type="text" ng-model="item.food" required/>
<button class="btn waves-effect waves-light addFood" ng-disabled="ret.$invalid" ng-click="submitted=true" ng-hide="submitted">Add</button>
<a class="btn waves-effect waves-light editFood" ng-click="submitted=false" ng-show="submitted"><i class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
<a ng-click="vm.removeFood(day); submitted=false">remove</a>
</form>
<div class="ingredients off" ng-class="{'show': submitted}">
<p>Ingredienser:</p>
<ul>
<li ng-repeat="ingredient in item.ingredients track by $index">
<button class="btn waves-effect waves-light" ng-click="vm.removeIngredient(day, ingredient); submitted=true">Add</button>
<span>{{ingredient.name}} ({{ingredient.amount}} {{ingredient.unit}})</span>
</li>
</ul>
<form name="ingredients_form" class="input-field">
<input placeholder="Ingredient" type="text" name="ingredients_name" ng-model="vm.ingredient[$index].name" value="" required/>
<input placeholder="Amount" type="number" ng-model="vm.ingredient[$index].amount" value="" required/>
<select ng-model="vm.ingredient[$index].unit" required>
<option value="" disabled selected>Choose your option</option>
<option value="g" title="gram">g</option>
<option value="kg" title="kilogram">kg</option>
<option value="l" title="liter">l</option>
</select>
</form>
<button class="btn waves-effect waves-light" ng-disabled="ingredients_form.$invalid" ng-click="vm.addIngredient(day, vm.ingredient[$index]); vm.ingredient[$index] = ''; ">Add</button>
</div>
</div>
<button class="restart" ng-click="vm.UnSave(); submitted=false">Restart</button>
</div>
</body>

I want AngularJS form only to display results after submit not while being completed

I want this app only to display results after submit button is pressed. At moment results show up as form is being completed. I'm using Angular.
HTML:
<html>
<div class="calc-page">
<div ng-app="myApp" ng-controller="myCtrl" class="hello">
<h2 class="text-center">Mark-up vs Gross Profit Calculator</h2>
<form action="action_page.php">
<p>Cost Price: <input type="text" ng-model="costPrice"></p><br>
<p>Sales Price: <input type="text" ng-model="salesPrice"></p><br>
<input value="Submit" class="btn btn-default hide-btn">
<input value="Clear" class="btn btn-default clear-btn">
</form>
<div class="results">
<p>Profit: {{(salesPrice - costPrice)}}</p>
<p>Gross Profit Margin: {{((salesPrice - costPrice) / salesPrice * 100)| number:0}}% </p>
<p>Mark Up: {{((salesPrice - costPrice) / costPrice * 100)| number:0 }}%</p>
</div>
</div>
</html>
JS:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.costPrice= 0;
$scope.salesPrice= 0;
});
CODEPEN: https://codepen.io/Jonod/pen/wKGLzO
Try the following (hiding the div until button is pressed or values in inputfield are changed):
<html>
<div class="calc-page">
<div ng-app="myApp" ng-controller="myCtrl" class="hello">
<h2 class="text-center">Mark-up vs Gross Profit Calculator</h2>
<form action="action_page.php">
<p>Cost Price: <input type="text" ng-change="submitted=false" ng-model="costPrice"></p><br>
<p>Sales Price: <input type="text" ng-change="submitted=false" ng-model="salesPrice"></p><br>
<input value="Submit" ng-click="submitted=true" class="btn btn-default hide-btn">
<input value="Clear" ng-click="clear()" class="btn btn-default clear-btn">
</form>
<div class="results" ng-if="submitted">
<p>Profit: {{(salesPrice - costPrice)}}</p>
<p>Gross Profit Margin: {{((salesPrice - costPrice) / salesPrice * 100)| number:0}}% </p>
<p>Mark Up: {{((salesPrice - costPrice) / costPrice * 100)| number:0 }}%</p>
</div>
</div>
</html>
And in the controller you could then add:
$scope.clear = function() {
$scope.costPrice= 0;
$scope.salesPrice= 0;
$scope.submitted=false;
}
You can try something like this:
HTML:
<html>
<div class="calc-page">
<div ng-app="myApp" ng-controller="myCtrl" class="hello">
<h2 class="text-center">Mark-up vs Gross Profit Calculator</h2>
<form action="action_page.php" ng-submit="call()">
<p>Cost Price: <input type="text" ng-model="costPrice"></p><br>
<p>Sales Price: <input type="text" ng-model="salesPrice"></p><br>
<input type="submit" value="Submit" class="btn btn-default hide-btn">
<input type="button" value="Clear" class="btn btn-default clear-btn" ng-click="clear()">
</form>
<div class="results" ng-if="show">
<p>Profit: {{(salesPrice - costPrice)}}</p>
<p>Gross Profit Margin: {{((salesPrice - costPrice) / salesPrice * 100)| number:0}}% </p>
<p>Mark Up: {{((salesPrice - costPrice) / costPrice * 100)| number:0 }}%</p>
</div>
</div>
</html>
JS:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.costPrice= 0;
$scope.salesPrice= 0;
$scope.show = false;
$scope.call = function() {
$scope.show = true;
}
$scope.clear = function() {
$scope.show = false;
$scope.costPrice= 0;
$scope.salesPrice= 0;
}
});
You can try like the below,
Template:
<form action="action_page.php">
<p>Cost Price: <input type="text" ng-model="costPriceModel"></p><br>
<p>Sales Price: <input type="text" ng-model="salesPriceModel"></p><br>
<input type="button" ng-click="getResult(costPriceModel, salesPriceModel);" value="Submit" class="btn btn-default hide-btn">
<input type="button" ng-click="clearResult()" value="Clear" class="btn btn-default clear-btn">
</form>
controller code:
$scope.getResult=function(a, b){
$scope.costPrice= a;
$scope.salesPrice= b;
}
$scope.clearResult=function(){
$scope.costPrice= 0;
$scope.salesPrice= 0;
}
You can:
remove form action attribute, you can create a request using the $http service. You don't want to go away from your single page app.
you can use and then reference the myForm in your scope. Like $scope.myForm.
you can check if the form was submitted by doing $scope.myForm.$submitted
you can check if your form is valid by adding novalidate to your form to disable HTML validation then check with $scope.myForm.$valid
you can reset the submitted state after you reset the form by doing $scope.myForm.$setPristine()
note that the <div> is shown if the form was submitted, but maybe is better to show the summary if the form was successfully submitted like keeping track of a flag $http.post('/action_page.php', {...}).then(() => $scope.isSubmittedSuccessfully = true).catch(() => $scope.isSubmittedSuccessfully = false).
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.costPrice= 0;
$scope.salesPrice= 0;
$scope.onSubmit = () => {
if(!$scope.myForm.$valid) {
return;
}
// note that this is not actually working as there is no /action_page.php
$http.post('/action_page.php', {
costPrice: $scope.costPrice,
salesPrice: $scope.salesPrice
})
.then(response => {
console.log('Submitted!');
})
.catch(error => {
console.log('Submit error!');
});
};
$scope.resetForm = () => {
$scope.costPrice= 0;
$scope.salesPrice= 0;
$scope.myForm.$setPristine();
};
});
/*$(function() {
$(".results").hide();
});
$(".hide-btn").click(function(){
$(".results").show();
});
$(".clear-btn").click(function(){
$(".results").hide();
$(this).closest('form').find("input[type=text], textarea").val("");
});*/
$primary-color: #36454f;
$font-stack: Helvetica, sans-serif;
$font-stack-head: Impact, sans-serif;
.hello {
padding: 50px;
height: 500px;
background-color: rgba(255, 255, 255, 0.5);
margin: auto;
width: 50%;
padding: 10px;
border-radius:10px;
color: $primary-color;
h2 {
font-family: Impact;
padding-bottom: 20px;
}
p {
font-size: 16px;
color: $primary-color;
}
}
.calc-page {
padding: 50px;
background-color: #e4ebec;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='32' height='32' viewBox='0 0 32 32'%3E%3Cg fill-rule='evenodd'%3E%3Cg id='Artboard-5' fill='%23ffffff' fill-opacity='0.4' fill-rule='nonzero'%3E%3Cpath d='M6 18h12V6H6v12zM4 4h16v16H4V4z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
};
.results {
padding: 30px 0 30px 0;
}
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>
<head>
<body>
<div class="calc-page">
<div ng-app="myApp" ng-controller="myCtrl" class="hello">
<h2 class="text-center">Mark-up vs Gross Profit Calculator</h2>
<form name="myForm" novalidate ng-submit="onSubmit()">
<p>Cost Price: <input type="number" ng-model="costPrice" required></p><br>
<p>Sales Price: <input type="number" ng-model="salesPrice" required></p><br>
<button type="submit" class="btn btn-default hide-btn">Submit</button>
<button type="button" class="btn btn-default clear-btn" ng-click="resetForm()">Clear</button>
</form>
<div class="results" ng-if="myForm.$submitted">
<p>Profit: {{(salesPrice - costPrice)}}</p>
<p>Gross Profit Margin: {{((salesPrice - costPrice) / salesPrice * 100)| number:0}}% </p>
<p>Mark Up: {{((salesPrice - costPrice) / costPrice * 100)| number:0 }}%</p>
</div>
</div>
</body>

What to send input text data to div

html Code
<div style="position: absolute; bottom: 0px; width: 100%">
<div style="text-align: center">
<div>
{{great}}
</div>
<form>
<div class="list">
<div class="list list-inset">
<label class="item item-input">
<input type="text" class="form-control input-lg" height="20" placeholder="Add Note" ng-model="searchText">
</label>
<button class="button button-block" ng-click="addTag()">Add Note</button>
</div>
</div>
</form>
app.js
$scope.searchText =" ";
$scope.great = "Note Here";
$scope.addTag = function () {
$scope.great == $scope.searchText;
};
I am trying to add a note to my tasks that I create. Here is my app:
https://behrouz2000.fwd.wf
When you click on the task and click a note it should create that note one on top of each other with a minute time stamp.
When you are assigning you should use one equal
$scope.great = $scope.searchText;
DEMO
var app = angular.module("myApp", []);
app.controller("myCtrl", ['$scope', function($scope) {
$scope.searchText ="Note Here";
$scope.great = [];
$scope.addTag = function () {
$scope.great = $scope.searchText;
};
}]);
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<script src="https://code.angularjs.org/1.4.7/angular.js"></script>
</head>
<body ng-controller="myCtrl">
<div style="position: absolute; bottom: 0px; width: 100%">
<div style="text-align: center">
<div>
{{great}}
</div>
<div class="list">
<div class="list list-inset">
<label class="item item-input">
<input type="text" class="form-control input-lg" height="20" placeholder="Add Note" ng-model="searchText">
</label>
<button class="button button-block" ng-click="addTag()">Add Note</button>
</div>
</div>
</div>
</div>
</body>
</html>

Add & delete note in AngularJS

I am new at AngularJS and I am trying to figure out how to add and delete notes to the setup that I have created. I have tried a lot of different things but I cant figure out how to get it to work.
I have cleaned up my code so it should be easier to figure out.
Please take a look at the jsfiddle version or snippet of my code:
'use strict'
var app = angular.module('plunker', ['ui.sortable']);
app.controller('MainCtrl', function($scope) {
var i;
$scope.itemsList = {
items1: [],
items2: []
};
for (i = 0; i <= 5; i += 1) {
$scope.itemsList.items1.push({
'Id': i,
'Label': 'Item ' + i
});
}
$scope.sortableOptions = {
containment: '#sortable-container',
accept: function(sourceItemHandleScope, destSortableScope) {
return sourceItemHandleScope.itemScope.sortableScope.$id === destSortableScope.$id;
}
};
});
.as-sortable-item,
.as-sortable-placeholder {} #sortable-container {} .touch-mover {
float: right;
padding: 3px;
margin-top: 5px;
}
<html ng-app="plunker">
<head>
<script data-require="angular.js#1.2.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js" data-semver="1.2.17"></script>
<script src="https://rawgithub.com/a5hik/ng-sortable/master/dist/ng-sortable.js"></script>
</head>
<body ng-controller="MainCtrl">
<div id="sortable-container">
<div class="form-actions">
<div class="input-append">
<form>
<input class="span3" size="16" type="text" placeholder="Add a note">
<button class="btn btn-success" type="button" ng-disabled="" ng-click="">
Add Note
</button>
</form>
</div>
</div>
<div class="sortable-row" as-sortable="sortableOptions" ng-model="itemsList.items1">
<div ng-repeat="item in itemsList.items1" class="simpel-fighter-input" as-sortable-item>
<input class="category-form textboxid" type="text" name="input" ng-model="item.Label" placeholder="Deltager1">
<div as-sortable-item-handle class="touch-mover">MOVE ME</div>
<a ng-click="" href>
<div class="touch-mover">DELETE</div>
</a>
<input class="category-form textboxid" style="float:right" type="text" name="input" ng-model="item.Label2" placeholder="Deltager2">
</div>
</div>
</div>
</body>
</html>
For adding a note just insert into your controller MainCtrl this function:
$scope.addNote = function() {
$scope.itemsList.items1.push({"Id" : $scope.itemsList.items1.length, "Label": "Item " + $scope.itemsList.items1.length})
}
and edit your form (add ng-model to input and ng-click function to button) like:
<input class="span3" size="16" type="text" ng-model="noteText" placeholder="Add a note">
<button class="btn btn-success" type="button" ng-disabled="" ng-click="addNote()">
Add Note
</button>
For deleting use in you controller something like
$scope.deleteNote = function(index) {
$scope.itemsList.items1.splice(index,1)
}
and attach this function to the tag "DELETE" like
ng-click="deleteNote($index)"
I hope this helps.

Resources