screenshot attached.
I learning angularJS.
And i can't find a way to remove the selected item that the 'Remove' button was click on.
Is there any way to do it ?
code attached:
<ul class="unstyled">
<li ng-repeat="todo in todos">
<input type="checkbox" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.text}}</span>
<button class="btn" ng-click="removeTodo()">Remove</button>
</li>
</ul>
var app = angular.module("app" , []);
app.controller("MyCtrl" , function($scope){
$scope.todos = [
{"text" :"Learn AngularJS","done":false},{"text" :"build an app","done":false}];
$scope.removeTodo = function(index) {
$scope.todos.splice(index,1);
}
$scope.removeTodo2 = function(todo) {
var index = getByValue( $scope.todos,todo);
$scope.todos.splice(index,1);
}
$scope.addTodo = function(todo){
var toDoObject = {"text":todo,"done":false};
$scope.todos.push(toDoObject);
};
$scope.done = function(todo){
angular.forEach($scope.todos,function(index,todo1){
if(todo == todo1)
$scope.todos[index].done = !$scope.todos[index].done;
})
}
function getByValue(arr, value) {
for (var i=0, iLen=arr.length; i<iLen; i++) {
if (arr[i].text == value) return i;
}
}
});
.done{
text-decoration: line-through;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MyCtrl">
<ul class="unstyled">
<li ng-repeat="todo in todos track by $index">
<input type="checkbox" ng-model="todo.done" >
<span ng-class="{'done' : todo.done == true}">{{todo.text}}</span>
<button class="btn" ng-click="removeTodo($index)">Remove</button>
<button class="btn" ng-click="removeTodo2(todo.text)">Remove2</button>
</li>
</ul>
<input type="text" ng-model="todo">
<input type="button" ng-click = "addTodo(todo)" value="Add">
</div>
Related
I have this ngRepeat. I want to create some sort of toggle, so that when the user clicks on the button, the input shows, however, I want all other shown inputs to hide (if they are already visible).
<ul>
<li ng-repeat="(key, value) in jewel">
<span ng-show="!showMe">text here</span>
<input ng-show="showMe">
<button ng-click="showMe = true"></button>
</li>
</ul>
Hope this makes sense.
ng-repeat has isolated scope, that is why to influence all other inputs you need to track their visibility via variable from parent scope. I've prepeared a fiddle with example: http://jsfiddle.net/ancvgc1b/
angular
.module('myApp', ['ui.bootstrap'])
.controller('ExampleController', function($scope){
$scope.jewel = {
key1: 'Foo',
key2: 'Bar'
};
$scope.visible = { key: 'key1' };
$scope.setVisible = function(key) {
$scope.visible.key = key;
}
});
<body ng-app="myApp">
<div ng-controller='ExampleController'>
<ul>
<li ng-repeat="(key, value) in jewel">
<span ng-show="!(visible.key == key)">Text value</span>
<input ng-show="visible.key == key">
<button ng-click="setVisible(key)">show input</button>
</li>
</ul>
</div>
</body>
Quick fix:
<ul ng-init="active={}">
<li ng-repeat="(key, value) in jewel">
<span ng-show="!($index==active.index)">text here</span>
<input ng-show="$index==active.index">
<button ng-click="active.index = $index"></button>
</li>
</ul>
If you are using controllerAs, it leads to much cleaner code as follows:
(vm is your alias to controller)
<ul>
<li ng-repeat="(key, value) in jewel">
<span ng-show="!($index==vm.activeIndex)">text here</span>
<input ng-show="$index==vm.activeIndex">
<button ng-click="vm.activeIndex = $index"></button>
</li>
</ul>
Try this :
var app = angular.module('myApp', []);
app.controller('MyCtrl',function($scope) {
$scope.people = [
{
id: 1,
name: "Alpha",
age: "24",
clicked : false
},
{
id: 2,
name: "Beta",
age: "25",
clicked : false
}
];
$scope.showInput = function(person,index) {
person.input = true;
$scope.index = index;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<ul>
<li ng-repeat="person in people">
<span ng-show="(!person.input && (index != $index))">text here</span>
<input ng-show="(person.input && (index == $index))">
<button ng-click="showInput(person,$index)">Show Input</button>
</li>
</ul>
</div>
controller as syntax problem
I am a newbie to angular, so please forgive me if i'm wrong. I have a problem where a service is used for certain operation. In this case, adding books to cart.
I have followed the recommended way using controller as syntax instead of $scope. But in kart-list.html, i'm not able to access kart details, since this operation is done by BookListCtrl.
app.js
var app = angular.module("app", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/books", {
templateUrl: "partials/book-list.html",
controller: "BookListCtrl",
controllerAs: 'booklist'
})
.when("/kart", {
templateUrl: "partials/kart-list.html",
controller: "KartListCtrl",
})
.otherwise({
redirectTo: "/books"
});
});
app.factory("kartService", function() {
var kart = [];
return {
getKart: function() {
return kart;
},
addToKart: function(book) {
kart.push(book);
},
buy: function(book) {
alert("Thanks for buying: ", book.name);
}
};
});
app.factory("bookService", function() {
var books = ['some data'];
return {
getBooks: function() {
return books;
},
addToKart: function(book) {
}
}
});
app.controller("KartListCtrl", function(kartService) {
var self = this;
self.kart = kartService.getKart();
self.buy = function(book) {
kartService.buy(book);
};
});
app.controller("HeaderCtrl", function() {
var self = this;
self.appDetails = {};
self.appDetails.title = "BooKart";
self.appDetails.tagline = "We have collection of 1 Million books";
});
app.controller("BookListCtrl", function(bookService, kartService) {
var self = this;
self.books = bookService.getBooks();
self.addToKart = function(book) {
kartService.addToKart(book);
};
});
book-list.html
<div id="bookListWrapper">
<form role="form">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search here..." />
</div>
</form>
<ul class="list-unstyled">
<li class="book" ng-repeat="book in booklist.books" style="background: white url('imgs/{{book.imgUrl}}') no-repeat">
<div class="book-details clearfix">
<h3>{{book.name}}</h3>
<p>{{book.price}}</p>
<ul class="list-unstyled list-inline">
<li>Rating: {{book.rating}}</li>
<li>Binding: {{book.binding}}</li>
<li>Publisher: {{book.publisher}}</li>
<li>Released: {{book.releaseDate}}</li>
</ul>
<p>{{book.details}}</p>
<button class="btn btn-info pull-right" ng-click="addToKart(book)">Add to Kart</button>
</div>
</li>
</ul>
</div>
kart-view.html
<div id="bookListWrapper">
<p>Please click on buy button to buy the book.</p>
<ul class="list-unstyled">
<li class="book" ng-repeat="book in kart" style="background: white url('imgs/{{book.imgUrl}}') no-repeat">
<div class="book-details clearfix">
<h3>{{book.name}}</h3>
<p>{{book.price}}</p>
<ul class="list-unstyled list-inline">
<li>Rating: {{book.rating}}</li>
<li>Binding: {{book.binding}}</li>
<li>Publisher: {{book.publisher}}</li>
<li>Released: {{book.releaseDate}}</li>
</ul>
<p>{{book.details}}</p>
<button class="btn btn-info pull-right" ng-click="buy(book)">Buy</button>
</div>
</li>
</ul>
</div>
Problem is how use controller as syntax for kart-list.html near ng-repeat to access kart details?
Your'e using the controller as feature but you haven't covered all view references.
book-list.html
<button ... ng-click="addToKart(book)">Add to Kart</button>
Change to
<button ... ng-click="booklist.addToKart(book)">Add to Kart</button>
kart-view.html
<li ... ng-repeat="book in kart" ...
...
<button ... ng-click="buy(book)">Buy</button>
Change to
<li ... ng-repeat="book in KartListCtrl.kart" ...
...
<button ... ng-click="KartListCtrl.buy(book)">Buy</button>
You have to prefix booklist while calling addToKart() method in book-list.html.
Use below file which will resolve your issue:
book-list.html
<div id="bookListWrapper">
<form role="form">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search here..." />
</div>
</form>
<ul class="list-unstyled">
<li class="book" ng-repeat="book in booklist.books" style="background: white url('imgs/{{book.imgUrl}}') no-repeat">
<div class="book-details clearfix">
<h3>{{book.name}}</h3>
<p>{{book.price}}</p>
<ul class="list-unstyled list-inline">
<li>Rating: {{book.rating}}</li>
<li>Binding: {{book.binding}}</li>
<li>Publisher: {{book.publisher}}</li>
<li>Released: {{book.releaseDate}}</li>
</ul>
<p>{{book.details}}</p>
<button class="btn btn-info pull-right" ng-click="booklist.addToKart(book)">Add to Kart</button>
</div>
</li>
</ul>
</div>
//Define angular app
var app = angular.module('ToDoApp', []);
//controllers
app.controller('taskController', function($scope) {
$scope.today = new Date();
$scope.saved = localStorage.getItem('taskItems');
$scope.taskItem = (localStorage.getItem('taskItems') !== null) ?
JSON.parse($scope.saved) : [{
description: "Why not add a task?",
date: $scope.today,
complete: false
}];
localStorage.setItem('taskItems', JSON.stringify($scope.taskItem));
$scope.newTask = null;
$scope.newTaskDate = null;
$scope.categories = [{
name: 'Personal'
}, {
name: 'Work'
}, {
name: 'School'
}, {
name: 'Cleaning'
}, {
name: 'Other'
}];
$scope.newTaskCategory = $scope.categories;
$scope.addNew = function() {
if ($scope.newTaskDate == null || $scope.newTaskDate == '') {
$scope.taskItem.push({
description: $scope.newTask,
date: "No deadline",
complete: false,
category: $scope.newTaskCategory.name
})
} else {
$scope.taskItem.push({
description: $scope.newTask,
date: $scope.newTaskDate,
complete: false,
category: $scope.newTaskCategory.name
})
};
$scope.newTask = '';
$scope.newTaskDate = '';
$scope.newTaskCategory = $scope.categories;
localStorage.setItem('taskItems', JSON.stringify($scope.taskItem));
};
$scope.deleteTask = function() {
var completedTask = $scope.taskItem;
$scope.taskItem = [];
angular.forEach(completedTask, function(taskItem) {
if (!taskItem.complete) {
$scope.taskItem.push(taskItem);
}
});
localStorage.setItem('taskItems', JSON.stringify($scope.taskItem));
};
$scope.save = function() {
localStorage.setItem('taskItems', JSON.stringify($scope.taskItem));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ToDoApp">
<div class="container">
<div class="content" ng-controller="taskController">
<h1>Welcome to your to do List</h1>
<p class="tagline">By Flintdesignz
</p>
<form>
<div class="row">
<div class="inputContainer">
<input type="text" id="description" class="taskName" placeholder="I need to..." ng-model="newTask">
</div>
</div>
<div class="row">
<div class="inputContainer"> <i class="fa fa-caret-down selectArrow"></i>
<select id="category" class="taskCategory" ng-model="newTaskCategory" ng-options="obj.name for obj in categories">
<option class="disabled" value="">Category</option>
</select>
</div>
</div>
<div class="row">
<div class="inputContainer">
<input type="date" id="dueDate" class="taskDate" ng-model="newTaskDate">
</div>
</div>
<div class="row buttons_holder">
<button class="taskAdd" ng-click="addNew()"><i class="fa fa-plus icon"></i>Add task</button>
<button class="taskDelete" ng-click="deleteTask()"><i class="fa fa-trash-o icon"></i>Remove Tasks</button>
</div>
</form>
<!-- TaskList Starts Here -->
<ul class="taskList">
<li class="taskItem" ng-repeat="taskItem in taskItem track by $index" ng-model="taskItem">
<input type="checkbox" class="taskCheckbox" ng-model="taskItem.complete" ng-change="save()">
<span class="complete-{{taskItem.complete}}">{{taskItem.description}}</span> <span class="category-{{taskItem.category}}">{{taskItem.category}}</span> <strong class="taskDate complete-{{taskItem.complete}}"><i class="fa fa-calendar"></i>{{taskItem.date | date : 'mediumDate'}}</strong>
</li>
</ul>
<!-- TaskList Ends HEre -->
</div>
<!-- Content Ends Here -->
</div>
<!-- container -->
</div>
Building a Todo App that adds tasks and deletes them aswell and getting the above error. Below is my html and my angular code. I have checked other blogs and still no valid answer.
Hi I was trying to run this angular based chat app, but it's giving me this error. Kindly please help me fix this.
the code is already available on
https://github.com/tamaspiros/AngularChat
the error i am getting is
Error: [ng:areq] Argument 'ChatAppCtrl' is not a function, got undefined
http://errors.angularjs.org/1.3.9/ng/areq?p0=ChatAppCtrl&p1=not%20a%20function%2C%20got%20undefined
at REGEX_STRING_REGEXP (angular.js:63)
at assertArg (angular.js:1577)
at assertArgFn (angular.js:1587)
at angular.js:8418
at angular.js:7592
at forEach (angular.js:331)
at nodeLinkFn (angular.js:7579)
at compositeLinkFn (angular.js:7075)
at compositeLinkFn (angular.js:7078)
at publicLinkFn (angular.js:6954)
the index.html is
<!DOCTYPE html>
<html ng-app="chat">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="css/bootstrap.yeti.css">
<link rel="stylesheet" href="css/flags.css">
<link rel="stylesheet" href="components/font-awesome/css/font-awesome.css">
</head>
<body ng-controller="ChatAppCtrl" ng-cloak>
<!-- Fixed navbar -->
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#" ng-click="about()">AngularChat</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>About</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><p class="navbar-text online" ng-if='status === "online"'>{{ status }}</p><p class="navbar-text offline" ng-if='status === "offline"'>{{ status }}</p></li>
<li class="dropdown" ng-show="joined">
{{ peopleCount }} online <b class="caret" ng-if="peopleCount > 0"></b>
<ul class="dropdown-menu">
<li ng-repeat="user in users"><p class="white">{{ user.name }} <span ng-if="user.countrycode"><img class="flag flag-{{user.countrycode}}"></span> <i class="fa fa-{{user.device}}"></i></p></li>
</ul>
</li>
<li class="dropdown" ng-show="joined">
{{ roomCount }} room<span ng-if="roomCount === 0 || roomCount > 1">s</span> <b class="caret" ng-if="roomCount > 0"></b>
<ul class="dropdown-menu">
<li ng-repeat="room in rooms">
<form class="form-inline" role="form"><div class="form-group"><p class="white">{{ room.name }}</p></div><button class="btn btn-success btn-xs" type="submit" ng-click='joinRoom(room)' ng-hide='room.id === user.owns || room.id === user.inroom || user.owns || user.inroom'>Join</button>
<button type="submit" ng-click='deleteRoom(room)' class="btn btn-xs btn-danger" ng-show='room.id === user.owns'>Delete</button>
<button type="submit" ng-click="leaveRoom(room)" class="btn btn-xs btn-info" ng-hide='room.id === user.owns || !user.inroom || user.owns || user.inroom !== room.id'>Leave</button></form>
</li>
</ul>
</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
<!-- Begin page content -->
<div class="container" ng-show="!joined">
<form class="form-inline" role="form">
<div class="form-group">
<label class="sr-only" for="username">Name: </label>
<input type="text" class="form-control" name="username" id="username" ng-model="username" placeholder="Enter desired name">
</div>
<button type="submit" class="btn btn-default btn-sm" ng-click='joinServer()'>Enter chat</button>
</form>
<small ng-if="error" class="text-danger">{{ error.join }}</small> <small ng-if="suggestedUsername" class="text-info" ng-click="setUsername(suggestedUsername)">How about <span class="text-success" style="cursor: pointer;">{{ suggestedUsername }}</a>?</small>
</div>
<div ng-hide="!joined" class="container" >
<p >Hello {{ user.name }}. <span ng-if="user.owns">You own a room: <strong>{{ user.roomname }}</strong>.</span> <span ng-if="!user.owns && user.inroom">You have joined a room: <strong>{{ user.roomname }}</strong>.<br> You can create your own room as well (but you need to leave the current one first)
</span><br>
<small ng-if="user.owns">You can remove your room by clicking delete in drop-down menu in the top right corner.</small></p>
<p ng-show="!user.inroom">Create a chat room or join one (top right corner).
<div id="createroom">
<form class="form-inline" role="form" ng-hide="user.owns && user.inroom">
<div class="form-group">
<label class="sr-only" for="roomname">Room name: </label>
<input type="text" placeholder="Enter room name" class="form-control" ng-model="roomname" name="roomname" id="roomname">
</div>
<button type="submit" class="btn btn-default btn-sm" ng-click="createRoom()">Create room</button>
<small ng-if="error" class="text-danger">{{ error.create }}</small>
</form>
</div>
<div id="chatpanel" ng-show="user.inroom" >
<div id="chat">
<form class="form-inline" role="form" ng-show="user.owns || user.inroom">
<div class="form-group">
<label class="sr-only" for="message">Message: </label>
<input type="text" placeholder="Enter message" class="form-control" ng-model="message" name="message" id="message" ng-keypress="typing($event, user.inroom)" on-focus="focus(true)" on-blur="focus(false)">
</div>
<button type="submit" class="btn btn-default btn-sm" ng-click='send()'>Send message</button>
</form>
<small ng-if="error" class="text-danger">{{ error.send }}</small>
</div>
<div class="row">
<div class="col-lg-6">
<div id="messages">
<ul>
<li class="list-unstyled" ng-repeat="message in messages track by $index" autoscroll ng-class="{dark: $index % 2 === 0}"><strong>{{ message.name }}</strong>: {{ message.message }}</li>
</ul>
</div>
</div>
<div class="col-lg-6">
<div id="sidebar">
<ul ng-if="isTyping">
<li ng-repeat="person in typingPeople track by $index" class="text-muted list-unstyled"><small>{{ person }} is typing</small></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="footer">
<div class="container">
<p class="text-muted">AngularChat by Tamas Piros | http://tamas.io/ | <a href="https://twitter.com/tpiros" target="_blank">#tpiros</p>
</div>
</div>
<!-- about modal -->
<script type="text/ng-template" id="aboutModal" />
<div class="modal-header">
<h3>About AngularChat</h3>
</div>
<div class="modal-body">
<p>Hello and thanks for visiting AngularChat.</p>
<p>This is an experimental project for testing new JavaScript technologies.</p>
<p>First, please enter your username. Once you've done this you have two options. You can create a room or you can join an already existing one.</p>
<p>Please note that once you've joined a room you can't create one (basically you can be part of one room at one time). Also note that if you're a room owner and you disconnect from the server, delete or leave your room all other participants will be removed from the room as well.</p>
<p>If you'd like to read more about the project please check out this article: http://tamas.io/angularchat/</p>
<p>If you're interested in the code behind this project, please go to: https://github.com/tamaspiros/angularchat</p>
</div>
<div class="modal-footer">
<button class="btn btn-warning btn-sm cancel" ng-click="cancel()">Cancel</button>
</div>
</div>
</script>
<script src="/socket.io/socket.io.js"></script>
<script src="components/angular/angular.js"></script>
<script src="components/angular-bootstrap/ui-bootstrap-tpls.js"></script>
<script src="components/jquery/dist/jquery.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/directives.js"></script>
<script src="js/services.js"></script>
</body>
</html>
and the function ChatAppCtrl is
'use strict';
function ChatAppCtrl($scope, $q, $modal, socket, useragent, geolocation) {
$scope.peopleCount = 0;
$scope.messages = [];
$scope.user = {}; //holds information about the current user
$scope.users = {}; //holds information about ALL users
$scope.rooms = []; //holds information about all rooms
$scope.error = {};
$scope.typingPeople = [];
$scope.username = '';
$scope.joined = false;
var typing = false;
var timeout = undefined;
/* ABOUT PAGE */
$scope.about = function() {
var modalInstance = $modal.open({
templateUrl: 'aboutModal',
controller: aboutModalCtrl
});
};
var aboutModalCtrl = function($scope, $modalInstance) {
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
};
/* ABOUT PAGE END */
$scope.setUsername = function(suggestedUsername) {
$scope.username = suggestedUsername;
}
function timeoutFunction() {
typing = false;
socket.emit('typing', false);
}
$scope.focus = function(bool) {
$scope.focussed = bool;
}
$scope.typing = function(event, room) {
if (event.which !== 13) {
if (typing === false && $scope.focussed && room !== null) {
typing = true;
socket.emit('typing', true);
} else {
clearTimeout(timeout);
timeout = setTimeout(timeoutFunction, 1000);
}
}
}
socket.on('isTyping', function(data) {
if (data.isTyping) {
$scope.isTyping = data.isTyping;
$scope.typingPeople.push(data.person);
} else {
$scope.isTyping = data.isTyping;
var index = $scope.typingPeople.indexOf(data.person);
$scope.typingPeople.splice(index, 1);
$scope.typingMessage = '';
}
});
$scope.joinServer = function() {
$scope.user.name = this.username;
if ($scope.user.name.length === 0) {
$scope.error.join ='Please enter a username';
} else {
var usernameExists = false;
socket.emit('checkUniqueUsername', $scope.user.name, function(data) {
usernameExists = data.result;
if (usernameExists) {
$scope.error.join = 'Username ' + $scope.user.name + ' already exists.';
socket.emit('suggest', $scope.user.name, function(data) {
$scope.suggestedUsername = data.suggestedUsername;
});
} else {
socket.emit('joinSocketServer', {name: $scope.user.name});
$scope.joined = true;
$scope.error.join = '';
}
});
}
}
$scope.send = function() {
if (typeof this.message === 'undefined' || (typeof this.message === 'string' && this.message.length === 0)) {
$scope.error.send = 'Please enter a message';
} else {
socket.emit('send', {
name: this.username,
message: this.message
});
$scope.message = '';
$scope.error.send = '';
}
}
$scope.createRoom = function() {
var roomExists = false;
var room = this.roomname;
if (typeof room === 'undefined' || (typeof room === 'string' && room.length === 0)) {
$scope.error.create = 'Please enter a room name';
} else {
socket.emit('checkUniqueRoomName', room, function(data) {
roomExists = data.result;
if (roomExists) {
$scope.error.create = 'Room ' + room + ' already exists.';
} else {
socket.emit('createRoom', room);
$scope.error.create = '';
if (!$scope.user.inroom) {
$scope.messages = [];
$scope.roomname = '';
}
}
});
}
}
$scope.joinRoom = function(room) {
$scope.messages = [];
$scope.error.create = '';
$scope.message = '';
socket.emit('joinRoom', room.id);
}
$scope.leaveRoom = function(room) {
$scope.message = '';
socket.emit('leaveRoom', room.id);
}
$scope.deleteRoom = function(room) {
$scope.message = '';
socket.emit('deleteRoom', room.id)
}
socket.on('sendUserDetail', function(data) {
$scope.user = data;
});
socket.on('listAvailableChatRooms', function(data) {
$scope.rooms.length = 0;
angular.forEach(data, function(room, key) {
$scope.rooms.push({name: room.name, id: room.id});
});
});
socket.on('sendChatMessage', function(message) {
$scope.messages.push(message);
});
socket.on('sendChatMessageHistory', function(data) {
angular.forEach(data, function(messages, key) {
$scope.messages.push(messages);
});
});
socket.on('connectingToSocketServer', function(data) {
$scope.status = data.status;
});
socket.on('usernameExists', function(data) {
$scope.error.join = data.data;
});
socket.on('updateUserDetail', function(data) {
$scope.users = data;
});
socket.on('joinedSuccessfully', function() {
var payload = {
countrycode: '',
device: ''
};
geolocation.getLocation().then(function(position) {
return geolocation.getCountryCode(position);
}).then(function(countryCode) {
payload.countrycode = countryCode;
return useragent.getUserAgent();
}).then(function(ua) {
return useragent.getIcon(ua);
}).then(function(device) {
payload.device = device;
socket.emit('userDetails', payload);
});
});
socket.on('updatePeopleCount', function(data) {
$scope.peopleCount = data.count;
});
socket.on('updateRoomsCount', function(data) {
$scope.roomCount = data.count;
});
socket.on('disconnect', function(){
$scope.status = 'offline';
$scope.users = 0;
$scope.peopleCount = 0;
});
}
Recent versions of Angular do not allow global functions to be used as controllers, see docs under "Arguments". The solutions:
(preferred) Use angular.module('chat').controller('ChatAppCtrl', ChatAppCtrl);
Configure the $controllerProvider: In a coonfig block, inject the $controllerProvider and run: $controllerProvider.allowGlobals().
I just want to delete the data inside the table using bootstrap modal, but it seems so hard to find the right way how to do this, here's my sample code. Inside my modal I have an href code that use to delete the data
, it is working outside the modal. I just want to know any solution make this working. thanks.
var app = angular.module('app', ['ui.bootstrap']);
var student = [{
name: 'Andrew'
}, {
name: 'Butler'
}, {
name: 'Cameron'
}, {
name: 'Delo'
}, {
name: 'Emman'
}, {
name: 'Ferbs'
}];
app.filter('startFrom', function() {
return function(input, start) {
if (input) {
start = +start; //parse to int
return input.slice(start);
}
return [];
}
});
app.controller('customersCtrl', function($scope, $timeout) {
$scope.list = student;
$scope.currentPage = 1; //current page
$scope.entryLimit = 10; //max no of items to display in a page
$scope.filteredItems = $scope.list.length; //Initially for no filter
$scope.totalItems = $scope.list.length;
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.filter = function() {
$timeout(function() {
$scope.filteredItems = $scope.filtered.length;
}, 10);
};
$scope.sort_by = function(predicate) {
$scope.predicate = predicate;
$scope.reverse = !$scope.reverse;
};
});
app.filter('startsWithA', function() {
return function(items, letter) {
console.log(items, letter)
var filtered = [];
var letterMatch = new RegExp(letter, 'i');
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (letterMatch.test(item.name.substring(0, 1))) {
filtered.push(item);
}
}
console.log(filtered);
return filtered;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.10.0/ui-bootstrap-tpls.js"></script>
<div ng-app="app">
<div class="container" ng-controller="customersCtrl">
<div class="row">
<div class="col-12">
<h2 id="titleHead"><center>Student List</center></h2>
</div>
<div class="option-panel">
<div class="col-sm-3 col-md-3 pull-right">
<form class="navbar-form">
<div class="input-group">
<input type="text" ng-model="search" ng-click="filter()" placeholder="Search student" class="form-control" placeholder="Search" name="search">
</div>
</form>
</div>
</div>
<div class="nav navbar-default">
<div class="tab-panel">
<nav>
<ul>
<li class="active" name="active"><a ng-click="letter = '[AB]'">A-B</a>
</li>
<li class="active" name="active"><a ng-click="letter = '[CD]'">C-D</a>
</li>
<li class="active" name="active"><a ng-click="letter = '[EF]'">E-F</a>
</li>
</ul>
</nav>
</div>
</div>
<div id="no-more-tables">
<table class="col-md-12 table-bordered table-condensed cf" ng-show="filteredItems > 0">
<thead class="cf">
<tr>
<th>
<center>Name
<a ng-click="sort_by('first_name');"></a>
</center>
</th>
</tr>
</thead>
<tbody color="#">
<tr ng-repeat="data in filtered = (list | filter:search |orderBy : predicate :reverse) | startFrom:(currentPage-1)*entryLimit |startsWithA:letter |limitTo:entryLimit ">
<td data-title="Name" class="text-center">{{data.name}} <a type="button" class="btn btn-xs btn-primary" style="width: 40%;" href="#" data-toggle="modal" data-target="#myModal" >Delete</a>
</td>
</tr>
</tbody>
</table>
<div class="col-md-12" ng-show="filteredItems == 0">
<div class="col-md-12">
<center>
<h4>No results found</h4>
</center>
</div>
</div>
<div class="col-md-12" ng-show="filteredItems > 0">
<center>
<div pagination="" page="currentPage" on-select-page="setPage(page)" boundary-links="true" total-items="filteredItems" items-per-page="entryLimit" class="pagination-small" previous-text="«" next-text="»"></div>
</center>
</div>
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Delete Student</h4>
</div>
<div class="modal-body">
<p>Do you want to delete this student?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">No</button>
<button type="button" class="btn btn-primary" href="<?php echo base_url(); ?>index.php/students/edit/studentform/{{data.id}}" >Yes</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
First I would suggest using $http service, or similar, for removing a record. Also, You'll notice that I made a change to the way your controller was organized by using the controller as syntax, and assigning everything to the controller, and not to the scope. That way you can pass on the controllers scope to directives and such more easily.
The idea is that you preserve an ID of the selected item, so that you can use it later on when you trigger the server delete action.
This can be done in many different ways, this is just one of the ways.
Hope this helps.
var app = angular.module('app', ['ui.bootstrap']);
var student = [{
id: 0,
name: 'Andrew'
}, {
id: 1,
name: 'Butler'
}, {
id: 2,
name: 'Cameron'
}, {
id: 3,
name: 'Delo'
}, {
id: 4,
name: 'Emman'
}, {
id: 5,
name: 'Ferbs'
}];
app.filter('startFrom', function() {
return function(input, start) {
if (input) {
start = +start; //parse to int
return input.slice(start);
}
return [];
}
});
app.controller('customersCtrl', function($http, $timeout) {
var vm = this,
itemId = null;
/**
* Store a selected item's ID
* #param id
*/
vm.getItemId = function (id) {
itemId = id;
};
/**
* Remove the selected item from the list
*/
vm.deleteItemFunction = function () {
console.log('remove', itemId);
// And then something like this
$http.delete('/students/edit/studentform/' + itemId).success(function () {
console.log('successfully removed');
});
};
vm.list = student;
vm.currentPage = 1; //current page
vm.entryLimit = 10; //max no of items to display in a page
vm.filteredItems = vm.list.length; //Initially for no filter
vm.totalItems = vm.list.length;
vm.setPage = function(pageNo) {
vm.currentPage = pageNo;
};
vm.filter = function() {
$timeout(function() {
vm.filteredItems = vm.filtered.length;
}, 10);
};
vm.sort_by = function(predicate) {
vm.predicate = predicate;
vm.reverse = !vm.reverse;
};
});
app.filter('startsWithA', function() {
return function(items, letter) {
console.log(items, letter)
var filtered = [];
var letterMatch = new RegExp(letter, 'i');
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (letterMatch.test(item.name.substring(0, 1))) {
filtered.push(item);
}
}
console.log(filtered);
return filtered;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.10.0/ui-bootstrap-tpls.js"></script>
<div ng-app="app">
<div class="container" ng-controller="customersCtrl as customer">
<div class="row">
<div class="col-12">
<h2 id="titleHead"><center>Student List</center></h2>
</div>
<div class="option-panel">
<div class="col-sm-3 col-md-3 pull-right">
<form class="navbar-form">
<div class="input-group">
<input type="text" ng-model="search" ng-click="customer.filter()" placeholder="Search student" class="form-control" placeholder="Search" name="search">
</div>
</form>
</div>
</div>
<div class="nav navbar-default">
<div class="tab-panel">
<nav>
<ul>
<li class="active" name="active"><a ng-click="letter = '[AB]'">A-B</a>
</li>
<li class="active" name="active"><a ng-click="letter = '[CD]'">C-D</a>
</li>
<li class="active" name="active"><a ng-click="letter = '[EF]'">E-F</a>
</li>
</ul>
</nav>
</div>
</div>
<div id="no-more-tables">
<table class="col-md-12 table-bordered table-condensed cf" ng-show="customer.filteredItems > 0">
<thead class="cf">
<tr>
<th>
<center>Name
<a ng-click="customer.sort_by('first_name');"></a>
</center>
</th>
</tr>
</thead>
<tbody color="#">
<tr ng-repeat="data in filtered = (customer.list | filter:search |orderBy : customer.predicate : customer.reverse) | startFrom:(customer.currentPage-1)* customer.entryLimit |startsWithA:letter |limitTo: customer.entryLimit ">
<td data-title="Name" class="text-center">
{{data.name}}
<a type="button" class="btn btn-xs btn-primary" style="width: 40%;" href="#" ng-click="customer.getItemId(data.id)" data-toggle="modal" data-target="#myModal">Delete</a>
</td>
</tr>
</tbody>
</table>
<div class="col-md-12" ng-show="customer.filteredItems == 0">
<div class="col-md-12">
<center>
<h4>No results found</h4>
</center>
</div>
</div>
<div class="col-md-12" ng-show="customer.filteredItems > 0">
<center>
<div pagination="" page="customer.currentPage" on-select-page="customer.setPage(page)" boundary-links="true" total-items="customer.filteredItems" items-per-page="customer.entryLimit" class="pagination-small" previous-text="«" next-text="»"></div>
</center>
</div>
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Delete Student</h4>
</div>
<div class="modal-body">
<p>Do you want to delete this student?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">No</button>
<button type="button" class="btn btn-primary" ng-click="customer.deleteItemFunction()">Yes</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>