What did I do wrong with my todo app? - angularjs

My todo app just doesn't work. It doesn't even display any pre-existing todo tasks on screen. Nor is it able to add or remove any items.
All it renders is the input form and submit button.
Why is that? Please advise!
var app = angular.module('todoApp',[])
app.controller('TodoController',['$scope', function($scope){
$scope.todos = [
{task: 'Learn AngularJs', done: false},
{task:'Feed the dog', done: false},
{task: 'Water the cactus', done: true}]
$scope.addTodo = function(){
$scope.todos.push({task: $scope.todoText, done: false});
$scope.todoText ='';
console.log($scope.todos);
}
$scope.removeTodo = function(){
var oldTodos = $scope.todos;
$scope.todos = [];
angular.forEach(oldTodos, function(todo) {
if (!todo.done) $scope.todos.push(todo);
});
}
}])
<!DOCTYPE html>
<html ng-app="todoApp">
<head>
<meta charset="utf-8"/>
<script src="bower_components/angular/angular.min.js"></script>
<script type="text/javascript" src="todo.js"></script>
<style>
.done-true{
text-decoration: line-through;
color: grey;
}
</style>
</head>
<body >
<div ng-controller="TodoController as todoList">
<ul class="unstyled">
<li ng-repeat="todo in todoList.todos">
<input type="checkbox" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.task}}</span>
</li>
</ul>
<form ng-submit="todoList.addTodo()">
<input type="text" placeholder="Add a new todo" ng-model="todoList.todoText">
<input type="button" type="submit" value="add">
</form>
<button ng-click="todoList.removeTodo()">Delete All</button>
</div>
</body>
</html>

remove todoList. while accessing variables and methods..
So your code should look like
<!DOCTYPE html>
<html ng-app="todoApp">
<head>
<meta charset="utf-8"/>
<script src="bower_components/angular/angular.min.js"></script>
<script type="text/javascript" src="todo.js"></script>
<style>
.done-true{
text-decoration: line-through;
color: grey;
}
</style>
</head>
<body >
<div ng-controller="TodoController">
<ul class="unstyled">
<li ng-repeat="todo in todos">
<input type="checkbox" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.task}}</span>
</li>
</ul>
<form>
<input type="text" placeholder="Add a new todo" ng-model="todoText">
<input type="button" ng-click="addTodo()" type="submit" value="add">
</form>
<button ng-click="todoList.removeTodo()">Delete All</button>
</div>
</body>
</html>

You are using MVVM method in your context so if you use controllerAs you need to use VM varibale is a scope in the controller instead of $scope variable. If you have any issues about MVC and MVVM please go through the reference link
http://www.dotnettricks.com/learn/designpatterns/understanding-mvc-mvp-and-mvvm-design-patterns
http://www.meritsolutions.com/mobile-development/mvvm-architectural-pattern-angularjs/
var app = angular.module('todoApp',[])
app.controller('TodoController',['$scope', function($scope){
var vm = this;
vm.todos = [
{task: 'Learn AngularJs', done: false},
{task:'Feed the dog', done: false},
{task: 'Water the cactus', done: true}]
vm.addTodo = function(){
if(vm.todoText)
vm.todos.push({task: vm.todoText, done: false});
vm.todoText ='';
console.log(vm.todos);
}
vm.removeTodo = function(){
var oldTodos = vm.todos;
vm.todos = [];
angular.forEach(oldTodos, function(todo) {
if (!todo.done) vm.todos.push(todo);
});
}
}])
.done-true{
text-decoration: line-through;
color: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="todoApp" ng-controller="TodoController as todoList">
<ul class="unstyled">
<li ng-repeat="todo in todoList.todos">
<input type="checkbox" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.task}}</span>
</li>
</ul>
<form >
<input type="text" placeholder="Add a new todo" ng-model="todoList.todoText">
<input type="button" type="button" value="add" ng-click="todoList.addTodo()">
</form>
<button ng-click="todoList.removeTodo()">Delete All</button>
</div>

Related

Upload an Image to a Web Api using AngularJS

Hi I'm new with Web API's and I'm working with AngularJS and Web API I'm trying to upload an image into a Web API but when I click the button to send the image it gives me an error
I already did the method GET and it shows me all the images that are in that web API but it doesn't work the method POST
here is my code
index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="stylesheet" href="css/bootstrap.css" media="screen">
<link rel="stylesheet" href="css/bootswatch.min.css">
</head>
<body>
<div ng-app="MarcasApp" >
<div ng-controller="MarcaController">
<div class="container">
<h2>Muestra</h2>
</div>
<input type="button" class="btn btn-info" value="Todos" ng-click="getTodos()">
<form name="formulario" method="post" action="" enctype="multipart/form-data">
<div class="container">
<label for="caption">Id:</label>
<input type="input" class="form-control" ng-model="txtId"/>
</div>
<div class="container">
<label for="caption">Cargar Marcar:</label>
<input type="file" ng-files="getTheFiles"/>
</div><br>
<div class="container">
<input type="submit" value="Enviar Marca" class="btn btn-success"
ng-click="btnGuardar()"/>
</div><br>
<div class="container">
Mensaje:{{msgGuardar}}
</div>
</form>
<div class="panel panel-info">
<ul class="list-group" ng-repeat="marca in marcas">
<li class="list-group-item">
<img src="{{marca.imagen}}">
{{marca.marca1}} + {{marca.marcaId}}
</li>
</ul>
</div>
</div>
</div>
<script src="js/jquery.min.js"></script>
<script src="js/angular.min.js"></script>
<script src="MarcaJson.js"></script>
</body>
</html>
MarcaJson.js
var app = angular
.module("MarcasApp", [])
.controller("MarcaController", function($scope, $http){
$scope.getTodos =function(){
var apiUrl = 'http://tiendawebapi.azurewebsites.net/api/marcas/';
$http.get(apiUrl).then(function(response){
$scope.marcas = response.data;
});
};
$scope.btnGuardar = function(){
var datos = {
id: $scope.txtId,
imagen: $scope.getTheFiles
}
var apiUrl = 'http://tiendawebapi.azurewebsites.net/api/marcas/';
$http.post(apiUrl, JSON.stringify(datos)).then(function(response){
if (response.statusText == Created){
$scope.msgGuardar = "Marca Guardada";
}
}, function(error){
$scope.msgGuardar = "Ocurrio un error " + error.statusText;
});
};
});

ng-disabled not functioning when used with an expression

<h2>Your TO DOs</h2>
<div class="list-group" ng-repeat="i in tasks track by $index">
<div href="#" class="list-group-item" style="overflow:auto;">
<span id={{$index}} style="background:{{i.priority}};padding:1%; border:#bfb9b9; border-style:dotted;">{{i.note}} </span>
<h5 style="float:right;">
<span>
<button class="btn-xs" style="border:none;background: cornflowerblue;" ng-disabled = '{{i.priority==="red"}}' ng-click = 'impTask(i)' >Imp</button>
ng-disabled = '{{i.priority==="red"}}' this line in the code isn't functioning though on inspection through DOM, its value is being displayed "true".
Here is the complete code
https://gist.github.com/7a3c7fd977c115638d386097f7c48b72.git
You should not use annotation with ng-disabled
Change
FROM
ng-disabled = '{{i.priority==="red"}}'
TO
ng-disabled = 'i.priority==="red"
DEMO
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.tasks = [{note:"Do the laundry", priority:'yellow'},{note:"Meeting at 10.00", priority:'yellow'}];
$scope.removeTask = function(task) {
var removedTask = $scope.tasks.indexOf(task);
$scope.tasks.splice(removedTask, 1);
};
$scope.addTask = function(){
if($scope.newTask!= null && $scope.newTask!= "" )
$scope.tasks.push({note:$scope.newTask,priority:'yellow'});
$scope.newTask= "";
};
$scope.impTask = function(task) {
var editedTask = $scope.tasks.indexOf(task);
$scope.tasks.splice(editedTask, 1);
task.priority= "red";
$scope.tasks.unshift(task);
};
});
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="myApp">
<div class="container" ng-controller="personCtrl" style="margin:5%;">
<div>
<form ng-submit="addTask()">
<input type="text" onClick="this.select()" placeholder="enter the task" ng-model="newTask"/>
<input type="submit" value="Add a new task" />
</form>
</div>
<h2>Your TO DOs</h2>
<div class="list-group" ng-repeat="i in tasks track by $index">
<div href="#" class="list-group-item" style="overflow:auto;">
<span id={{$index}} style="background:{{i.priority}};padding:1%; border:#bfb9b9; border-style:dotted;">{{i.note}} </span>
<h5 style="float:right;" >
<span>
<button class="btn-xs" style="border:none;background: cornflowerblue;" ng-disabled = 'i.priority==="red"' ng-click = 'impTask(i)' >Imp</button>
</span>
<span>
<button class="btn-xs" style="border:none;background: cornflowerblue; " ng-click = 'strikeTask(i)'>Done</button>
</span>
<span>
<button class="btn-xs" style="border:none;background: cornflowerblue;" ng-click = 'editTask(i)' >Edit</button>
</span>
<a ng-click="removeTask(i)" style="padding-left:5px; padding-right:5px; color: red; font-weight: 800; background:#dad4d4";>X</a>
</div>
</div>
</body>
</html>

How to get the checked item inside a ng-repeat using angular?

I want to get the check item from a list withing a ng-repeat in angular. Once the item is checked I want to put that checked item to another list.Here is my code so far.
<div class="col-lg-12" data-ng-repeat="user in users track by $index">
<div class="col-lg-12">
<div class="col-lg-3"> {{user.name}} </div>
<div class="col-lg-3">
<input type="checkbox" data-ng-checked="selectUser(user)" data-ng-model="user.isSelected" />
</div>
</div>
</div>
<div class="col-lg-12" data-ng-repeat="selectedUser in selectedUsers track by $index">
<div class="col-lg-12">
<div class="col-lg-3"> {{selectedUser.name}} </div>
<div class="col-lg-3">
</div>
</div>
</div>
This is my controller function to get the checked users.
$scope.selectUser = function(user){
if (user.isSelected) {
if ($scope.selectedUsers.indexOf(user.id) === -1) {
$scope.selectedUsers.push(user);
}
}else {
var index = $scope.selectedUsers.indexOf(user.id);
if ($scope.selectedUsers.indexOf(user.id) != -1) {
$scope.selectedUsers.splice(index, 1);
}
}
When I check a checkbox, all the users value will be passed to selectUsers() function. And it will give incorrect result. I want only to get the selected users. How can I do this?
Some mistakes you made here
You are using ng-check in wrong way.
Try this
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.allUsers = [{
id:0,
name:'john',
age:26,
selectedUser:true
},{
id:1,
name:'isha',
age:23,
selectedUser:false
},{
id:2,
name:'scott',
age:34,
selectedUser:true
},{
id:3,
name:'riya',
age:26,
selectedUser:false
},{
id:4,
name:'Adam',
age:5,
selectedUser:true
},{
id:5,
name:'doe',
age:56,
selectedUser:true
},{
id:6,
name:'Jack',
age:22,
selectedUser:true
},{
id:7,
name:'robin',
age:11,
selectedUser:true
}];
$scope.selectedUsers = [];
$scope.selectUser = function(user){
if (user.isSelected) {
$scope.selectedUsers.push(user);
}else {
for (var i = 0; i < $scope.selectedUsers.length; i++) {
if ($scope.selectedUsers[i].id == user.id) {
$scope.selectedUsers.splice(i, 1);
}
}
}
}
})
</script>
</head>
<body style="margin-top: 100px" ng-app="myApp" ng-controller="myCtrl">
<div class="col-lg-12" data-ng-repeat="user in allUsers track by $index">
<div class="col-lg-12">
<div class="col-lg-3"> {{user.name}} </div>
<div class="col-lg-3">
<input type="checkbox" ng-change="selectUser(user)" data-ng-model="user.isSelected" />
</div>
</div>
</div>
selected users
<div class="col-lg-12" data-ng-repeat="user in selectedUsers track by $index">
<div class="col-lg-12">
<div class="col-lg-3"> {{user.name}} </div>
<div class="col-lg-3">
</div>
</div>
</div>
</body>
</html>
Try this I think u need like this
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $window) {
$scope.Fruits = [{
FruitId: 1,
Name: 'Apple',
Selected: false
}, {
FruitId: 2,
Name: 'Mango',
Selected: false
}, {
FruitId: 3,
Name: 'Orange',
Selected: false
}];
$scope.GetValue = function () {
var message = "";
for (var i = 0; i < $scope.Fruits.length; i++) {
if ($scope.Fruits[i].Selected) {
var fruitId = $scope.Fruits[i].FruitId;
var fruitName = $scope.Fruits[i].Name;
message += "Value: " + fruitId + " Text: " + fruitName + "\n";
}
}
$window.alert(message);
}
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<div ng-repeat="fruit in Fruits">
<label for="chkCustomer_{{fruit.FruitId}}">
<input id="chkCustomer_{{fruit.FruitId}}" type="checkbox" ng-model="fruit.Selected" />
{{fruit.Name}}
</label>
</div>
<br />
<br />
<input type="button" value="Get" ng-click="GetValue()" />
</div>
</body>
</html>

why does my form submission not work?

I just want to use the two way binding to update my list by adding new elements to it. I don't understand why i can't do it? am i missing a major concept?
index.html
<!DOCTYPE html>
<html>
<head>
<title>NgRailsTodoList</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body ng-app="todoApp" ng-controller="MainCtrl">
<div class="container">
<div class="content-container clearfix">
<div class="col-md-12">
<h1 class="content-title text-center">Todo</h1>
<div ng-repeat="list in lists">
<h3>{{list.name}}</h3>
<div ng-repeat="task in list.tasks">
<h5><input type="checkbox" ng-checked="task.completed">{{ task.body }}</h5>
</div>
<div>
</div>
<form ng-submit="addList()">
<input type="text" ng-model="name"></input>
<button type="submit"> New List </button>
</form>
</div>
</div>
</body>
</html>
app.js
angular.module('todoApp', ['ui.router', 'templates'])
.factory('lists',[ function () {
var o = { lists: [{ name: "groceries", completed: false,
tasks: [{body: "buy fish",completed: true},
{body: "buy sushi",completed: false},
{body: "buy bread",completed: true}]}]
};
return o;
}])
.controller('MainCtrl', [
'$scope','lists',
function($scope,lists){
console.log(lists);
$scope.lists = lists.lists;
$scope.addList = function(){
$scope.lists.push({name: $scope.name, completed: false})
// console.log(this.name);
// $scope.name = '';
};
}
]);
The issue is in the markup.
<h5><input type="checkbox" ng-checked="task.completed">{{ task.body }}</h5>
</div>
<div>
</div>
the second <div> should be a close tag </div>
here is a working example http://codepen.io/mkl/pen/KzEmwP

Refreshing data after a JSON call in Angular

I have an angular model which gets the data through a JSON call and shows as follows. After making a second JSON how can I refresh this list.
<ul ng-repeat="x in names">
<h3> {{ x.name }} </h3>
<h4> {{ x.place }} </h4>
<p> <img ng-src="{{x.image}}"> </p>
</ul>
I inject the data initially through this:
$http.get("").success(function (response) {$scope.names = courseParsed;});
You can check it out below.
http://findcourse.parseapp.com/
I am adding the full code to make it easier, through the "Select and Search" Button ($scope.names[0].name = "test"; $scope.names.splice(1, 1)), I am trying to modify the list, even though it worked once, now it is not working at all.
var app = angular.module('myApp', []);
var queryParam ={};
app.controller('customersCtrl', function($scope, $http, $q) {
Parse.$ = jQuery;
Parse.initialize("mvLeLP1wbRJW24ESjaUEgPueWHpMLNZNvwLnTTJW", //"applicationId":
"NqwHrO9MjC9uLgqu4zNIi6u9TC19GVRbMmNxXTag"); //JavaScript Key
var Article = Parse.Object.extend('coursesParse');
$scope.master = {};
$scope.update = function(user) {
//$scope.master = angular.copy(user);
//alert(user.degree+" "+user.industry);
//alert($scope.names[0].name);
$scope.names[0].name = "test";
$scope.names.splice(1, 1);
};
var myLat = -37.875773;
var myLng = 145.087829;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getPosition);
} else {
alert("Please allow using your location to see the courses around you!");
}
function getPosition(position) {
myLat = position.coords.latitude;
myLng = position.coords.longitude;
var mapOptions = {
center: new google.maps.LatLng(myLat, myLng),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
}
var ArticleDfd = $q.defer();
var queryInitial = new Parse.Query(Article);
//queryInitial.equalTo('name', 'Electrical Supply');
var geoPoint = ({latitude: myLat, longitude: myLng});
queryInitial.near("coords", geoPoint);
queryInitial.limit(4);
queryInitial.find().then(function (data) {
var courseParsed = [];
for (var i = 0; i < data.length; i++) {
courseParsed[i] = {
"name": data[i].get('name'),
"description": data[i].get('description'),
"length": data[i].get('length'),
"place": data[i].get('place'),
"comment": data[i].get('comments'),
"image": data[i].get('images'),
"webLink": data[i].get('weblink'),
"xCor": data[i].get('coords').latitude,
"yCor": data[i].get('coords').longitude
};
//for (var prop in courseParsed[i]) {alert(prop + " = "+ courseParsed[i][prop])};
}
for(var i=0;i<courseParsed.length;i++){
//alert(courseParsed[i]['xCor'], courseParsed[i]['yCor']);
//alert(courseParsed[i]['xCor']);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(courseParsed[i]['xCor'], courseParsed[i]['yCor']),
//icon: "img/icon.png",
map: map,
title: 'Hello World!'
});
}
ArticleDfd.resolve(data);
$http.get("").success(function (response) {$scope.names = courseParsed;});
}, function (error) {
ArticleDfd.reject(data);
});
ArticleDfd.promise
.then(function (article) {
$scope.currentArticle = article;
})
.catch(function (error) {
//do something with the error
});
});
HTML page:
<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script src="http://www.parsecdn.com/js/parse-1.2.13.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="js/controllers.js"></script>
<script src="js/effect.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<link rel="stylesheet" href="css/app.css">
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<div id="map">Loading...</div>
<div id="searchForm" ng-controller="customersCtrl">
<form novalidate>
<select type="text" ng-model="user.degree">
<option>Diploma</option><option>Advanced Diploma</option><option>Certificate III</option>
</select>
<select type="text" ng-model="user.industry">
<option>Finance</option><option>Construction</option><option>Energy and Power</option>
</select>
<!-- Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<input type="button" ng-click="reset()" value="Reset" />
<pre>user = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>-->
<input type="submit" ng-click="update(user)" value="Select and Search" />
</form>
</div>
<ul ng-repeat="x in names">
<h3> {{ x.name }} </h3>
<h4> {{ x.place }} </h4>
<p> <img ng-src="{{x.image}}"> </p>
</ul>
<!--<p> {{ x.length + ', ' + x.description }}
<p> {{ x.comment }} </p> </p> -->
</div>
</body>
</html>
All you have to do is to move your ul inside the div above.
<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script src="http://www.parsecdn.com/js/parse-1.2.13.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="js/controllers.js"></script>
<script src="js/effect.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<link rel="stylesheet" href="css/app.css">
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<div id="map">Loading...</div>
<div id="searchForm" ng-controller="customersCtrl">
<form novalidate>
<select type="text" ng-model="user.degree">
<option>Diploma</option><option>Advanced Diploma</option><option>Certificate III</option>
</select>
<select type="text" ng-model="user.industry">
<option>Finance</option><option>Construction</option><option>Energy and Power</option>
</select>
<!-- Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<input type="button" ng-click="reset()" value="Reset" />
<pre>user = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>-->
<input type="submit" ng-click="update(user)" value="Select and Search" />
</form>
<ul ng-repeat="x in names">
<h3> {{ x.name }} </h3>
<h4> {{ x.place }} </h4>
<p> <img ng-src="{{x.image}}"> </p>
</ul>
</div>
</div>
</body>
</html>
after calling second JSON. assign result to 'names' variable. then use following code
$route.reload();
I think you need to place your $http call in $scope.getData function & call it again whenever you wanted to reload data. ng-repeat will do the magic for you of refreshing data as any change occurred in names object. Basically any change in names will render those many ul's on view.

Resources