AngularJS two different actions in ng-submit - javascript

I'm new to AngularJS, currently I am trying to create a spa for tracking expenses as a simple project but I have some problems with my code.
I managed to do the most of the function but I got stuck at the update function, I want to be able to update the data without creating another button, instead using the same submit button which is used to add new data
Here is the html and js code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Expenses Tracker</title>
<link rel="stylesheet" href="bootstrap.min.css">
<link href="style.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<span class="navbar-brand"><img src="logo.png" class="brand" height="40" />
Simple Expenses App Tracker</span>
</div>
</div>
</nav>
<div class="main" ng-app="myList" ng-controller="myListController">
<img src="logo.png" class="logo">
<form ng-submit="newItem()" class="form">
<input required type="number" placeholder="Amount" ng-model="amount">
<input required type="text" placeholder="Description" ng-model="description">
<input type="submit" value="Submit" class="btn btn-success">
</form>
<ul>
<li ng-repeat="item in items">
<span class="pull-left"> {{item.amount}} den.</span> {{item.description}}
<span class="buttons">
<input type="button" ng-click="editItem($index)" value="Edit" class="btn btn-primary" >
<input type="button" ng-click="deleteItem($index)" value="Delete" class="btn btn-danger">
</span>
</li>
<br>
<li><span class="total">{{totalPrice()}} den.</span> <span class="expense"> Total Expenses</span></li>
</ul>
</div>
<script src="bootstrap.min.js"></script>
<script src="angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="app.js"></script>
</body>
</html>
var myApp = angular.module("myList", []);
myApp.controller("myListController", function($scope) {
$scope.items = [];
$scope.newItem = function() {
$scope.items.push({description:$scope.description, amount: $scope.amount});
$scope.description = '';
$scope.amount = 0
};
$scope.deleteItem = function(index) {
$scope.items.splice(index, 1);
}
$scope.totalPrice = function() {
var total = 0;
for(count=0; count<$scope.items.length;count++){
total += $scope.items[count].amount;
}
return total;
};
$scope.editItem = function(index) {
$scope.amount = $scope.items[index].amount;
$scope.description = $scope.items[index].description;
};
});

You could have two scope variables to keep track if in edit mode and to keep track of the index that is being edited, and in the newItem() can have an if else statement based on edit mode or not
For example you could do something like
var myApp = angular.module("myList", []);
myApp.controller("myListController", function($scope) {
$scope.items = [];
$scope.isEdit = false; // initialize
$scope.editingIndex = null; //initialize
$scope.newItem = function() {
if(!$scope.isEdit){ //if not in edit mode -> add new
$scope.items.push({description:$scope.description, amount: $scope.amount});
}
else{ //in edit mode -> edit the object
$scope.items[$scope.editingIndex] = { //replace with new values
description:$scope.description, amount: $scope.amount
}
$scope.isEdit = false; //setting back to false
$scope.editingIndex = null;
}
$scope.description = '';
$scope.amount = 0
};
$scope.deleteItem = function(index) {
$scope.items.splice(index, 1);
}
$scope.totalPrice = function() {
var total = 0;
for(count=0; count<$scope.items.length;count++){
total += $scope.items[count].amount;
}
return total;
};
$scope.editItem = function(index) {
$scope.isEdit = true; //setting edit mode true
$scope.editingIndex = index; //setting the index to edit
$scope.amount = $scope.items[index].amount;
$scope.description = $scope.items[index].description;
};
});
demo

Related

Not able to get the number of correct answers calculated for a Javascript Simple Quiz

I am trying to create a sample Quiz where I need to calculate the number of correct answers which I have stored in Score variable.
But facing issues. Any help will highly be appreciated
Below is the code
window.addEventListener('DOMContentLoaded', () => {
const start = document.querySelector('#start');
start.addEventListener('click', function(e) {
document.querySelector('#quizBlock').style.display = 'block';
start.style.display = 'none';
});
// quizArray QUESTIONS & ANSWERS
// q = QUESTION, o = OPTIONS, a = CORRECT ANSWER
// Basic ideas from https://code-boxx.com/simple-javascript-quiz/
const quizArray = [{
q: 'Which one of the following is the capital of USA?',
o: ['New York', 'Washington DC', 'California', 'Las Vegas'],
a: 1, // array index 1 - so Earth is the correct answer here
},
{
q: 'Which is the highest mountain on Earth?',
o: ['K2', 'Annapurna', 'Makalu', 'Everest'],
a: 3,
},
{
q: 'What is the capital of Sweden',
o: ['Spain', 'Stockholm', 'Portugal', 'Hawai'],
a: 1,
},
{
q: 'What is Shawarma',
o: ['Drink', 'Food', 'Animal', 'Place'],
a: 1,
},
];
// function to Display the quiz questions and answers from the object
const displayQuiz = () => {
const quizWrap = document.querySelector('#quizWrap');
let quizDisplay = '';
quizArray.map((quizItem, index) => {
quizDisplay += `<ul class="list-group">
Q - ${quizItem.q}
<li class="list-group-item mt-2" id="li_${index}_0"><input type="radio" name="radio${index}" id="radio_${index}_0"> ${quizItem.o[0]}</li>
<li class="list-group-item" id="li_${index}_1"><input type="radio" name="radio${index}" id="radio_${index}_1"> ${quizItem.o[1]}</li>
<li class="list-group-item" id="li_${index}_2"><input type="radio" name="radio${index}" id="radio_${index}_2"> ${quizItem.o[2]}</li>
<li class="list-group-item" id="li_${index}_3"><input type="radio" name="radio${index}" id="radio_${index}_3"> ${quizItem.o[3]}</li>
</ul>
<div> </div>`;
quizWrap.innerHTML = quizDisplay;
});
};
//Event listener for the submit button
const btn = document.getElementById('btnSubmit');
btn.addEventListener('click', function(event) {
const totalScore = calculateScore(this);
console.log('Button Clicked');
console.log('Total Score' + totalScore);
});
// Calculate the score
const calculateScore = () => {
let score = 0;
quizArray.map((quizItem, index) => {
for (let i = 0; i < 4; i++) {
//highlight the li if it is the correct answer
let li = `li_${index}_${i}`;
let r = `radio_${index}_${i}`;
liElement = document.querySelector('#' + li);
radioElement = document.querySelector('#' + r);
if (i == 0 && r == 1)
score = score++;
if (i == 1 && r == 3)
score = score++;
if (i == 2 && r == 1)
score = score++;
if (i == 3 && r == 1)
score = score++;
console.log('Score In Loop ', score);
if (quizItem.a == i) {
//change background color of li element here
}
if (radioElement.checked) {
// code for task 1 goes here
}
}
});
};
// call the displayQuiz function
displayQuiz();
console.log("Score=" + score);
});
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous" />
<title>Quiz</title>
</head>
<body>
<div class="container m-5" id="start">
<div class="card" style="width: 18rem">
<div class="card-body">
<h5 class="card-title">Test your knowledge</h5>
<p class="card-text">Some quick description about the quiz .</p>
<a class="btn btn-primary">Start</a>
</div>
</div>
</div>
<!-- (B) QUIZ CONTAINER -->
<div class="container" id="quizBlock" style="display: none">
<div class="mb-5">
<h2>Test your knowledge</h2>
- Time remaining <span id="time">01:00</span>
</div>
<div id="quizWrap"></div>
<div>
<button type="button" class="btn btn-primary" id="btnSubmit">
Submit Quiz
</button>
<button type="button" class="btn btn-primary" id="btnReset">
Reset Quiz
</button>
<span id="score"></span>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="./js/index.js"></script>
</body>
</html>
I also need to highlight the correct answer with a different colour.
I am very new to Javascript so help will highly be appreciated
Don't hard-code the checks for correct answers in the loop. When the radio button is checked, test if i matches quizItem.a. If it does, increment the score. At the same time you can highlight the selected answer with different colors depending on whether it's correct or not.
If it's not checked and is the correct answer, you can then highlight it with a third color.
The syntax for incrementing a variable is either score = score + 1 or score++. Don't combine them, it doesn't work.
window.addEventListener('DOMContentLoaded', () => {
const start = document.querySelector('#start');
start.addEventListener('click', function(e) {
document.querySelector('#quizBlock').style.display = 'block';
start.style.display = 'none';
});
// quizArray QUESTIONS & ANSWERS
// q = QUESTION, o = OPTIONS, a = CORRECT ANSWER
// Basic ideas from https://code-boxx.com/simple-javascript-quiz/
const quizArray = [{
q: 'Which one of the following is the capital of USA?',
o: ['New York', 'Washington DC', 'California', 'Las Vegas'],
a: 1, // array index 1 - so Earth is the correct answer here
},
{
q: 'Which is the highest mountain on Earth?',
o: ['K2', 'Annapurna', 'Makalu', 'Everest'],
a: 3,
},
{
q: 'What is the capital of Sweden',
o: ['Spain', 'Stockholm', 'Portugal', 'Hawai'],
a: 1,
},
{
q: 'What is Shawarma',
o: ['Drink', 'Food', 'Animal', 'Place'],
a: 1,
},
];
// function to Display the quiz questions and answers from the object
const displayQuiz = () => {
const quizWrap = document.querySelector('#quizWrap');
let quizDisplay = '';
quizArray.map((quizItem, index) => {
quizDisplay += `<ul class="list-group">
Q - ${quizItem.q}
<li class="list-group-item mt-2" id="li_${index}_0"><input type="radio" name="radio${index}" id="radio_${index}_0"> ${quizItem.o[0]}</li>
<li class="list-group-item" id="li_${index}_1"><input type="radio" name="radio${index}" id="radio_${index}_1"> ${quizItem.o[1]}</li>
<li class="list-group-item" id="li_${index}_2"><input type="radio" name="radio${index}" id="radio_${index}_2"> ${quizItem.o[2]}</li>
<li class="list-group-item" id="li_${index}_3"><input type="radio" name="radio${index}" id="radio_${index}_3"> ${quizItem.o[3]}</li>
</ul>
<div> </div>`;
quizWrap.innerHTML = quizDisplay;
});
};
//Event listener for the submit button
const btn = document.getElementById('btnSubmit');
btn.addEventListener('click', function(event) {
const totalScore = calculateScore(this);
console.log('Button Clicked');
console.log('Total Score = ' + totalScore);
});
// Calculate the score
const calculateScore = () => {
let score = 0;
quizArray.map((quizItem, index) => {
for (let i = 0; i < 4; i++) {
//highlight the li if it is the correct answer
let li = `li_${index}_${i}`;
let r = `radio_${index}_${i}`;
liElement = document.querySelector('#' + li);
radioElement = document.querySelector('#' + r);
if (radioElement.checked) {
if (quizItem.a == i) {
score++;
liElement.style.backgroundColor = 'green';
} else {
liElement.style.backgroundColor = 'red';
}
} else if (quizItem.a == i) {
liElement.style.backgroundColor = 'yellow';
}
console.log('Score In Loop ', score);
}
});
return score;
};
// call the displayQuiz function
displayQuiz();
});
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous" />
<title>Quiz</title>
</head>
<body>
<div class="container m-5" id="start">
<div class="card" style="width: 18rem">
<div class="card-body">
<h5 class="card-title">Test your knowledge</h5>
<p class="card-text">Some quick description about the quiz .</p>
<a class="btn btn-primary">Start</a>
</div>
</div>
</div>
<!-- (B) QUIZ CONTAINER -->
<div class="container" id="quizBlock" style="display: none">
<div class="mb-5">
<h2>Test your knowledge</h2>
- Time remaining <span id="time">01:00</span>
</div>
<div id="quizWrap"></div>
<div>
<button type="button" class="btn btn-primary" id="btnSubmit">
Submit Quiz
</button>
<button type="button" class="btn btn-primary" id="btnReset">
Reset Quiz
</button>
<span id="score"></span>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="./js/index.js"></script>
</body>
</html>

Angular add value from dropdown into list and from list into dropdown

I have problems with the functionality of my code when I add persons from dropdow into the list or from the list back to the dropdown then alot of bugs occurs e.x the same person get added 2 times or when I delete one person then an otherone gets deleted instead, and I'm not sure where the bug/mistake is, maybe you can help me out.
Fiddle
HTML:
<div ng-app="miniapp">
<div ng-controller="Ctrl">
<div ng-init="getPersons()" class="dropdown">
<select name="selectedPerson" ng-model="selectedPerson">
<option ng-repeat="Person in Persons">{{Person}}</option>
</select>
<button ng-click="addPerson()">
<div>
<i class="fa fa-plus"></i>
</div>
</button>
</div>
<div class="block-form ng-scope" ng-init="initSavedPersons()">
<ul class="pers-ul">
<li class="pers-li" ng-repeat="person in persons | orderBy:'name'">
<span class="fa" ng-click="getDeletedPerson($event); deletePerson($index)"></span>
<span>{{person.name}}</span>
</li>
</ul>
</div>
</div>
Controller:
var $scope;
var app = angular.module("myapp", []);
app.controller("Ctrl", function($scope) {
$scope.persons = [];
$scope.Persons = [];
var deletedPers = "";
$scope.getPersons = function() {
$scope.Persons = ["Tom", "Jerry"];
};
$scope.initSavedPersons = function() {
var initPers = ["Max", "Alfi"];
for (var i = 0; i < initPers.length; i++) {
$scope.persons.push({ name: initPers[i] });
}
};
$scope.addPerson = function() {
var index = 0;
$scope.persons.push({ name: $scope.selectedPerson });
for (var i = 0; i < $scope.Persons.length; i++) {
if ($scope.Persons[i] == $scope.selectedPersons) {
index = i;
}
}
console.log(index);
$scope.Persons.splice(index, 1);
$scope.Persons.sort();
};
$scope.getDeletedPerson = function(obj) {
deletedPers = obj.currentTarget.nextElementSibling.innerHTML;
};
$scope.deletePerson = function(index) {
$scope.persons.splice(index, 1);
$scope.Persons.push(deletedPers);
};
});
Here's your code without external libraries and bug fixes. I have commented before the changes.
var $scope;
var app = angular.module("myapp", []);
app.controller("Ctrl", function($scope) {
// changed the variable names so they are easy to identify.
$scope.addedPersons = [];
$scope.dropDownPersons = [];
// added it outside the function initSavedPersons
$scope.initPers = ["Max", "Alfi"];
$scope.getPersons = function() {
$scope.dropDownPersons = ["Tom", "Jerry"];
};
$scope.initSavedPersons = function() {
// used map function to generate array
$scope.addedPersons = $scope.initPers.map(function(item){
return { name: item };
});
};
$scope.addPerson = function() {
$scope.addedPersons.push({ name: $scope.selectedPerson });
// use findIndex function
var index = $scope.dropDownPersons.findIndex(function(item) {
return item == $scope.selectedPerson;
});
$scope.dropDownPersons.splice(index, 1);
$scope.dropDownPersons.sort();
};
// deleted unnecessary function getDeletedPerson
// passed the deleting object to the function
$scope.deletePerson = function(deletingPerson) {
// used findIndex again
var index = $scope.addedPersons.findIndex(function(item) {
return item.name == deletingPerson.name;
});
// add to dropdown
$scope.dropDownPersons.push(deletingPerson.name);
$scope.addedPersons.splice(index, 1);
};
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page 1</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
</head>
<body>
<div ng-app="myapp">
<div ng-controller="Ctrl">
<div ng-init="getPersons()" class="dropdown">
<select name="selectedPerson" ng-model="selectedPerson">
<option ng-repeat="dropDownPerson in dropDownPersons">{{dropDownPerson}}</option>
</select>
<button ng-click="addPerson()">
<div>
<i class="fa fa-plus"></i>
</div>
</button>
</div>
<div class="block-form ng-scope" ng-init="initSavedPersons()">
<ul class="pers-ul">
<li class="pers-li" ng-repeat="addedPerson in addedPersons | orderBy:'name'">
<span class="fa" ng-click="deletePerson(addedPerson)"></span>
<span>{{addedPerson.name}}</span>
</li>
</ul>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
</body>
</html>
I used lodash to manipulate arrays. Please check the code below;
var $scope;
var app = angular.module('myapp', []).constant('_', window._);
function Ctrl($scope) {
$scope.persons = [];
$scope.Persons = [];
var deletedPers = "";
$scope.getPersons = function () {
$scope.Persons = ["Tom", "Jerry"];
}
$scope.initSavedPersons = function () {
var initPers = ["Max", "Alfi"];
initPers.sort();
for (var i = 0; i < initPers.length; i++) {
$scope.persons.push({ 'name': initPers[i] });
}
}
$scope.addPerson = function () {
var index = 0;
$scope.persons.push({ 'name': $scope.selectedPerson });
var sortedArray = _.sortBy($scope.persons, ['name']);
$scope.persons.length = 0;
$scope.persons.push.apply($scope.persons, sortedArray);
_.remove($scope.Persons, function(item) { return item == $scope.selectedPerson});
}
$scope.deletePerson = function (index) {
console.log(index);
var deletedPerson = Object.assign({}, $scope.persons[index]);
_.remove($scope.persons, { 'name' : deletedPerson.name});
$scope.Persons.push(deletedPerson.name);
$scope.Persons.sort();
}
}
.pers-ul {
list-style: none;
padding-left: 0;
margin-top: 25px;
}
.pers-li {
border: 1px solid black;
display: inline-block;
padding: 5px 10px;
margin-right: 5px;
margin-bottom: 5px;
text-transform: capitalize;
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.10/lodash.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<div ng-app="myapp">
<div ng-controller="Ctrl">
<div ng-init="getPersons()" class="dropdown">
<select name="selectedPerson" ng-model="selectedPerson">
<option ng-repeat="Person in Persons">{{Person}}</option>
</select>
<button ng-click="addPerson()">
<div>
<i class="fa fa-plus"></i>
</div>
</button>
</div>
<div class="block-form ng-scope" ng-init="initSavedPersons()">
<ul class="pers-ul">
<li class="pers-li" ng-repeat="person in persons">
<span class="fa" ng-click="deletePerson($index)"></span>
<span>{{person.name}}</span>
</li>
</ul>
</div>
</div>
</div>

AngularJs, How to edit $scope values in other div using the same controller with factory

I would like to use two different divs one contains a form and other contains repeat for the $scope values. Those two divs needs to use the same controller. However I am not able to share data in between divs in a desired way. Although I use factory, it only helps for me to add data to scope. I also want to edit the scope values inside the form which has another instance of the same controller.
You can find what I did in this link.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<body>
<script>
var app = angular.module("myShoppingList", []);
app.factory('fact',function(){
products = ["milk","chese"];
tempItem = '';
tempIndex = undefined;
return {
getProducts : function() {
return products;
},
getProductByIndex : function(x){
return products[x];
},
saveProduct : function(x,item)
{
if(x==undefined)
{
products.push(item);
}
else
{
products[x] = item;
}
tempItem = '';
tempIndex = undefined;
},
editProduct : function(x)
{
tempItem = products[x];
tempIndex = x;
},
removeProduct : function(x)
{
products.splice(x, 1);
},
getTempItem : function()
{
return tempItem;
},
getTempIndex : function()
{
return tempIndex;
},
}
});
app.controller("myCtrl", function($scope, fact) {
$scope.products = fact.getProducts();
$scope.tempIndex = fact.getTempIndex();
$scope.tempItem = fact.getTempItem();
$scope.saveItem = function () {
fact.saveProduct($scope.tempIndex,$scope.tempItem);
}
$scope.editItem = function (x) {
fact.editProduct(x);
}
$scope.removeItem = function (x) {
fact.removeProduct(x);
}
});
</script>
<div ng-app="myShoppingList" ng-cloak class="w3-card-2 w3-margin" style="max-width:400px;">
<header class="w3-container w3-light-grey w3-padding-16">
<h3>My Shopping List</h3>
</header>
<div ng-controller="myCtrl">
<ul class="w3-ul">
<li ng-repeat="x in products" class="w3-padding-16">{{$index}} {{x}}
<span ng-click="editItem($index)" style="cursor:pointer;" class="w3-right w3-margin-right">||</span>
<span ng-click="removeItem($index)" style="cursor:pointer;" class="w3-right w3-margin-right">×</span>
</ul>
</div>
<div ng-controller="myCtrl" class="w3-container w3-light-grey w3-padding-16">
<form ng-submit="saveItem()">
<div class="w3-row w3-margin-top">
<div class="w3-col s10">
<input placeholder="Add shopping items here" ng-model="tempItem" class="w3-input w3-border w3-padding">
<input type="hidden" ng-model="tempIndex">
</div>
<div class="w3-col s2">
<button type="submit" class="w3-btn w3-padding w3-green">Save</button>
</div>
</div>
</form>
</div>
</div>
</body>
</html>
ISSUES
You have initialized controller twice.
You can do edit item inside controller itself.
After saving $scope values should be cleared along with clearing values in factory.
CONTROLLER and HTML
var app = angular.module("myShoppingList", []);
app.factory('fact',function(){
products = ["milk","chese"];
tempItem = '';
tempIndex = undefined;
return {
getProducts : function() {
return products;
},
getProductByIndex : function(x){
return products[x];
},
saveProduct : function(x,item)
{
if(!x)
{
products.push(item);
}
else
{
products[x] = item;
}
tempItem = '';
tempIndex = '';
},
editProduct : function(x)
{
tempItem = products[x];
tempIndex = x;
},
removeProduct : function(x)
{
products.splice(x, 1);
},
getTempItem : function()
{
return tempItem;
},
getTempIndex : function()
{
return tempIndex;
},
}
});
app.controller("myCtrl", function($scope, fact) {
$scope.products = fact.getProducts();
$scope.tempIndex = fact.getTempIndex();
$scope.tempItem = fact.getTempItem();
$scope.saveItem = function () {
fact.saveProduct($scope.tempIndex,$scope.tempItem);
$scope.tempItem = '';
$scope.tempIndex = '';
}
$scope.editItem = function (x) {
$scope.tempItem = fact.getProducts()[x];
$scope.tempIndex = x;
}
$scope.removeItem = function (x) {
fact.getProducts().splice(x, 1);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<div ng-app="myShoppingList" ng-controller="myCtrl" ng-cloak class="w3-card-2 w3-margin" style="max-width:400px;">
<header class="w3-container w3-light-grey w3-padding-16">
<h3>My Shopping List</h3>
</header>
<div>
<ul class="w3-ul">
<li ng-repeat="x in products" class="w3-padding-16">{{$index}} {{x}}
<span ng-click="editItem($index)" style="cursor:pointer;" class="w3-right w3-margin-right">||</span>
<span ng-click="removeItem($index)" style="cursor:pointer;" class="w3-right w3-margin-right">×</span>
</ul>
</div>
<div class="w3-container w3-light-grey w3-padding-16">
<form ng-submit="saveItem()">
<div class="w3-row w3-margin-top">
<div class="w3-col s10">
<input placeholder="Add shopping items here" ng-model="tempItem" class="w3-input w3-border w3-padding">
<input type="hidden" ng-model="tempIndex">
</div>
<div class="w3-col s2">
<button type="submit" class="w3-btn w3-padding w3-green">Save</button>
</div>
</div>
</form>
</div>
</div>

Cannot display angularJS scope components

I am making a web application using AngularJS and Laravel. The application is meant to allow the user to post a note on a board. With the code I have, when submitting the note it gets saved to the database but it does not display on the page.
angulartest.blade.php:
<!doctype html>
<html lang="en" ng-app="app">
<title>Test angular</title>
<link rel="stylesheet" href="css/bootstrap.css">
<body>
<div class="container" ng-controller="NoteController">
<h3>Add note</h3>
<form ng-submit="addNote()">
<input type="text" ng-model="newNote.content">
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<ul>
<li ng-repeat="note in notes">
#{{ note.content }}
</li>
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
app.js
var app = angular.module('app', ['ngRoute']);
app.factory('Data', function Data($http) {
return {
getNotes: function getNotes() { return $http.get('/notes/all'); },
addNote: function addNote(data) { return $http.post('/notes', data); },
removeNote: function removeNote(id) { return $http.delete('/notes?id='+ id); }
}
});
app.controller('NoteController', function NoteController($scope, Data) {
Data.getNotes().success(parseNotes);
function parseNotes(data) {
$scope.notes = data;
}
$scope.newNote = { content: '', poster: '' };
$scope.addNote = function addNote() {
Data.addNote({
content: $scope.newNote.content,
poster: $scope.newNote.post
})
.success(noteAddSuccess).error(noteAddError);
}
function noteAddSuccess(data) {
$scope.error = null;
$scope.notes.push(data);
console.log($scope.notes);
$scope.newNote = { content: '', poster: '' };
}
function noteAddError(data) {
$scope.error = data;
}
$scope.removeNote = function removeNote(id) {
if (confirm('Do you really want to remove this note?')) {
Data.removeNote(id).success(noteRemoveSuccess);
}
}
function noteRemoveSuccess(data) {
var i = $scope.notes.length;
while (i--) {
if ($scope.notes[i].id == data) {
$scope.notes.splice(i, 1);
}
}
}
});
I believe this is all the relevant code. I'm not sure why it is not displaying note.content
Thank you
Since the data update is not triggered from UI, i.e on user clicks or similar activity the scope might be unaware of the changes. In your code you are updating the data from the service, thus my first suggestion will be is to use $scope.$apply() to propagate the changes on the model to the UI.
function parseNotes(data) {
$scope.notes = data;
if (!$scope.$$phase) {
$scope.$apply();
}
}
This might help. If not then, please post back
I found my error, really simple. I was closing div tag before I was requesting {{note.content}}. It should look like:
<div class="container" ng-controller="NoteController">
<h3>Add note</h3>
<form ng-submit="addNote()">
<input type="text" ng-model="newNote.content">
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<ul>
<li ng-repeat="note in notes">
#{{ note.content }}
</li>
</ul>
</div>
thank you for the replies!

how to generate list dynamically in angular.js

can you please tell me how to create list dynamically in angulat.js..Actullly I am able to make list when user press add button and fill the field .
In other words ,Please check this fiddle whenever you fill the fields it generate a row.And you can get Id when you click the row .Fiddle http://jsfiddle.net/wc4Jm/6/
Now I am trying to do this using bootstrap model .in other words on button click first I show a pop up screen then there is "add" button .on click that it generate the row.but I am getting "undefined".My I insert the model div inside the controller ? here is
http://jsbin.com/vubojoxo/4/
Why I am getting this error ?
XMLHttpRequest cannot load file:///C:/Users/asd/Desktop/angular/angularproject/dialog.html. Received an invalid response. Origin 'null' is therefore not allowed access.
I am getting this error when I used plunker..and run in my desktop ..
I make this html ?
<!doctype html>
<html ng-app="plunker">
<head>
<script src="angular.js"></script>
<script src="ui-bootstrap-tpls-0.2.0.js"></script>
<link href="bootstrap-combined.min.css" rel="stylesheet">
<script src="index.js"></script>
</head>
<body>
<div ng-controller="DialogDemoCtrl">
<a class="btn" data-toggle="modal" href="" ng-click="openPopupScreen()">Add Contend</a>
</div>
</body>
</html>
....
Dialog.html
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h1>Add Element</h1>
</div>
<div class="modal-body">
<form >
<label>Name:</label><input type="text" class="span3" ng-model="activeItem.name"></br>
<label>Content Name:</label><input type="password" class="span3" ng-model="activeItem.content"></br>
<button type="submit" class="btn btn-success" ng-click="addItem()">Add In List</button>
<button type="reset" class="btn ">Clear</button>
</form>
</div>
<div class="modal-footer">
<a class="btn" data-dismiss="modal" aria-hidden="true">close</a>
</div>
js code:
var myApp = angular.module('plunker', ['ui.bootstrap']);
myApp.controller('DialogDemoCtrl', function($scope,$dialog) {
$scope.items = [];
$scope.activeItem = {
id:'',
name: '',
content: ''
};
$scope.addItem = function () {
$scope.activeItem.id = $scope.items.length + 1;
$scope.items.push($scope.activeItem);
$scope.activeItem = {}; /* reset active item*/
};
$scope.getId = function (item) {
alert('ID: '+item.id);
};
$scope.openPopupScreen = function () {
alert('Check Open pop up screen');
$dialog.dialog({}).open('dialog.html');
};
});
Check this Plunker
In this example i used angular-ui library which wraps bootstrap's modal to angular
based on this StackOverflow Answer
ModalDemoCtrl
$scope.items = [];
$scope.getId = function(item) {
alert('ID: ' + item.id);
};
// This opens a Bootstrap modal
$scope.open = function() {
var modalInstance = $modal.open({
template: $scope.modal_html_template,
controller: ModalInstanceCtrl
});
modalInstance.result.then(function(newItem) {
// On modal success
newItem.id = $scope.items.length + 1;
$scope.items.push(newItem);
}, function() {
// On modal cancelation
});
}
ModalInstanceCtrl
$scope.name = '';
$scope.content = '';
$scope.ok = function() {
var response = {
'name': $scope.name,
'content': $scope.content
};
$modalInstance.close(response);
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
HTML
<body>
<div ng-controller="ModalDemoCtrl">
<div inner-html-bind="" inner-html="modal_html_template" class="hidden">
<div class="modal-header">
<h3>I'm a modal!</h3>
</div>
<div class="modal-body">
<div class="form-group">
<label>Name</label>
<!-- using $parent because ui-bootstrap nested 2 controllers. this is a workaround -->
<input type="text" class="form-control" ng-model="$parent.name" placeholder="Enter Name">
</div>
<div class="form-group">
<label>Content</label>
<!-- using $parent because ui-bootstrap nested 2 controllers. this is a workaround -->
<input type="text" class="form-control" ng-model="$parent.content" placeholder="Enter Content">
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</div>
<div class="container">
<h2>Modal Example https://stackoverflow.com/questions/24988561</h2>
<button class="btn" ng-click="open()">Open Modal</button>
<div>
<ul>
<li ng-repeat="item in items">
<a ng-click="getId(item)">{{ item.id }} | {{ item.name + ' ' + item.content }}</a>
</li>
</ul>
</div>
</div>
</div>
</body>

Categories

Resources