how to put css in selected row in angular js? - javascript

i am creating a todo list in angularjs.. its almost done.. my question is when i click on edit button, i want to highlight full row which is in editing mode by adding a css class "yellow"...
but i have no idea how to do this...
and can anybody tell me is my way of coding is right or worng.. please
jsfiddle link
http://jsfiddle.net/mcVfK/1338/
here is my code
html
<div ng-app="myapp">
<div class="container" ng-controller="mainCtrl">
<h3>Todo List</h3>
<input type="text" class="form-control" placeholder="create your todos" ng-model="newItem">
<p class="help-block text-center red" ng-show="!newItem && empty">*Fill the field.</p>
<br>
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Todo</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="todoList in todoLists">
<td>{{$index+1}}</td>
<td>{{todoList.name}}</td>
<td>{{todoList.edit}}</td>
<td><a class="btn {{disabled}} pull-right" href="" ng-click="remove(todoList)">delete</a>
<a class="btn {{disabled}} pull-right" href="" ng-click="edit($index)">edit</a> </td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-primary btn-lg btn-block" ng-click="add()" ng-hide="editMode">ADD</button>
<button type="button" class="btn btn-default btn-lg btn-block" ng-click="update(newItem)" ng-show="editMode">UPDATE</button>
</div>
</div>
my js file
var app = angular.module("myapp", []);
app.controller("mainCtrl", ["$scope", "$rootScope", function($scope, $rootScope){
$scope.empty = false;
$scope.editMode = false;
$scope.todoLists = [{name : "one", edit : "false"},{name : "two", edit : "false"}];
$scope.add = function(){
if(!$scope.newItem == ""){
$scope.todoLists.push({name:$scope.newItem, edit:"false"});
$scope.newItem = "";
$scope.empty = false;
}else{
$scope.empty = true;
};
};
$scope.remove = function(item){
var index = $scope.todoLists.indexOf(item);
$scope.todoLists.splice(index, 1);
};
$scope.edit = function(index){
$rootScope.ind = index;
$scope.newItem = $scope.todoLists[$rootScope.ind].name;
$scope.editMode = true;
$scope.disabled = "disabled";
$scope.todoLists[index].edit = "true";
};
$scope.update = function(item){
if(!$scope.newItem == ""){
$scope.todoLists[$rootScope.ind].name = item;
$scope.todoLists[$rootScope.ind].edit = "false";
$scope.editMode = false;
$scope.newItem = "";
$scope.disabled = "";
}else{
$scope.empty = true;
};
};
}]);
css file
.yellow{
background:yellow;
}
.red{
color:red;
}

You can make use of ng-class directive provided by AngularJS.
https://docs.angularjs.org/api/ng/directive/ngClass
Change
<tr ng-repeat="todoList in todoLists">
to
<tr ng-repeat="todoList in todoLists" ng-class="{yellow: editMode && $index == ind}">

Quick and ugly example, based on your fiddle. You basically want to use ng-class to run a function that returns a class if a condition is met. In this case, when you select a todo to edit, you can set that as the selectedTodo on $scope:
$scope.edit = function(index){
$scope.selectedToDo = $scope.todoLists[index];
....
};
And then you can set an ng-class on your <tr> element that will check if that row's todo is selected and return a class, .highlighted in this case, if it is.
$scope.isSelected = function(item) {
if ($scope.selectedToDo === item) {
return 'highlighted';
}
};

Simple example use of ng-class using the red class you already have in demo
<tr ng-repeat="todoList in todoLists"
ng-class="{red:active.item == todoList}"
ng-click="active.item=todoList">
In controller
$scope.active={item:null}

There is one more way to assign different class for different rows
ng-class-odd="'odd'" ng-class-even="'even'"
code below
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
css
.odd {
color: red;
}
.even {
color: blue;
}
but the only thing is this directive can be applied only within the scope of an ngRepeat.
Hope this will help you..

There are many ways to implement this.A quick solution would be to pass the $event through the edit method of the particular row.
<a class="btn {{disabled}} pull-right" href="" ng-click="edit($index,$event)">edit</a> </td>
Then your can use $event.target to access the clicked element. You can then use angular.element($event.target).parent().parent() to access the row element.
Edit function
var EditRow;
$scope.edit = function(index,$event){
EditRow = angular.element($event.target).parent().parent();
EditRow.css( "background-color", "#ccc"); // change css style
$rootScope.ind = index;
$scope.newItem = $scope.todoLists[$rootScope.ind].name;
$scope.editMode = true;
$scope.disabled = "disabled";
$scope.todoLists[index].edit = "true";
};
Update function
$scope.update = function(item){
if(!$scope.newItem == ""){
$scope.todoLists[$rootScope.ind].name = item;
$scope.todoLists[$rootScope.ind].edit = "false";
$scope.editMode = false;
$scope.newItem = "";
$scope.disabled = "";
}else{
$scope.empty = true;
};
EditRow.css( "background-color", "#fff"); //We change the style back
};
Here is a working fiddle.

I've updated the jsfiddle for u: http://jsfiddle.net/mv0ne441/
You can use ng-class directive in the table's 'tr' element for the whole row highlighting as you said in the question
<tr ng-repeat="todoList in todoLists" ng-class="{true:'yellow', false:'red'} [todoList.edit == 'true']">
<td>{{$index+1}}</td>
<td>{{todoList.name}}</td>
<td>{{todoList.edit}}</td>
<td><a class="btn {{disabled}} pull-right" href="" ng-click="remove(todoList)">delete</a>
<a class="btn {{disabled}} pull-right" href="" ng-click="edit($index)">edit</a>
</td>
</tr>

You just need to use ng-class to add css class at run time based on selectedIndex, which holds the index of current row in edit mode.
HTML Code:
<tr ng-repeat="todoList in todoLists" ng-class="{'yellow':selectedIndex== $index }">
Angular JS Code:
$scope.edit = function(index) {
$scope.selectedIndex = index;
...
};
//clear the selectedIndex to negative index -1
$scope.update = function(item) {
if (!$scope.newItem == "") {
$scope.selectedIndex = -1;
...
};
Live Demo #JSFiddle

i have added the update code here please have a look on it .
you should have to use ng-class.
var app = angular.module("myapp", []);
app.controller("mainCtrl", ["$scope", "$rootScope",
function($scope, $rootScope) {
$scope.empty = false;
$scope.editMode = false;
$scope.todoLists = [{
name: "one",
edit: "false",
"todoeditclick": false
}, {
name: "two",
edit: "false",
"todoeditclick": false
}];
$scope.add = function() {
if (!$scope.newItem == "") {
$scope.todoLists.push({
name: $scope.newItem,
edit: "false"
});
$scope.newItem = "";
$scope.empty = false;
} else {
$scope.empty = true;
};
};
$scope.remove = function(item) {
var index = $scope.todoLists.indexOf(item);
$scope.todoLists.splice(index, 1);
};
$scope.edit = function(index) {
$rootScope.ind = index;
$scope.newItem = $scope.todoLists[$rootScope.ind].name;
$scope.editMode = true;
$scope.disabled = "disabled";
$scope.todoLists[index].edit = "true";
};
$scope.update = function(item) {
if (!$scope.newItem == "") {
$scope.todoLists[$rootScope.ind].name = item;
$scope.todoLists[$rootScope.ind].edit = "false";
$scope.todoLists[$rootScope.ind].todoeditclick = false;
$scope.editMode = false;
$scope.newItem = "";
$scope.disabled = "";
} else {
$scope.empty = true;
};
};
}
]);
.yellow {
background: yellow;
}
.red {
color: red;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="myapp">
<div class="container" ng-controller="mainCtrl">
<h3>Todo List</h3>
<input type="text" class="form-control" placeholder="create your todos" ng-model="newItem">
<p class="help-block text-center red" ng-show="!newItem && empty">*Fill the field.</p>
<br>
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Todo</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="todoList in todoLists" ng-class="{yellow:todoList.todoeditclick}">
<td>{{$index+1}}</td>
<td>{{todoList.name}}</td>
<td>{{todoList.edit}}</td>
<td><a class="btn {{disabled}} pull-right" href="" ng-click="remove(todoList)">delete</a>
<a class="btn {{disabled}} pull-right" href="" ng-click="edit($index);todoList.todoeditclick=!todoeditclick">edit</a>
</td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-primary btn-lg btn-block" ng-click="add()" ng-hide="editMode">ADD</button>
<button type="button" class="btn btn-default btn-lg btn-block" ng-click="update(newItem)" ng-show="editMode">UPDATE</button>
</div>
</div>

Related

How to select and deselect an div / button in angularJs?

I am trying to make items not in list but in div and if an item is clicked, the div will be in different colors and the item will be added into a column but if the item is clicked again, the item will changed to original color and in the column the item will be gone. I just can't think how to do it in angular way. I came to another option to be able to add in the column and to remove the item, there's a remove button but I am still curious how the select and deselect can be done.
This is what I have in my html (ignore my btn btn-primary classes I was using button to give it a try in the first place)
<!--Select App Features-->
<div class="panel-heading" ng-controller="FeaturesController as featuresCtrl">
<h1 class="text-center">App Features</h1>
<div class="text-center">
<div ng-repeat="app in featuresCtrl.apps" class="btn btn-primary platform-btn-style" ng-click="featuresCtrl.addPrices(app.name, app.price)">{{ app.name }}</div><br>
</div>
<div>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Device Added</th>
<th>Device Price</th>
<th></th>
</tr>
</thead>
<tr ng-repeat="appList in featuresCtrl.listAppPrices">
<td>{{ appList.name }}</td>
<td>{{ appList.price }}</td>
<td><button class="btn btn-default" ng-click="featuresCtrl.remove($index)">Remove</button></td>
</tr>
</table>
<div>Total : {{ featuresCtrl.totalAppPrice() }}</div>
</div>
</div><!-- end select app features / FeaturesController-->
My controller in js
//Controller for app features
app.controller("FeaturesController", function(){
this.apps = features;
this.listAppPrices = [];
// add name and price into the new array which is used to show in the table
this.addPrices = function(name, price){
//Checks if the exact name, price property exists in the array and return boolean
var found = this.listAppPrices.some(function (e){
console.log(e.name);
return ((e.name === name) && (e.price === price)) ;
});
//If found not true then push the new values into the array
if(!found){
this.listAppPrices.push({name: name, price: price});
}
};
// adds all the prices of the array which gives the total
this.totalAppPrice = function(){
var total = 0;
for(var i = 0; i < this.listAppPrices.length; i++){
total += this.listAppPrices[i].price;
}
return total;
};
// remove the whole object in the array when remove is clicked
this.remove = function(index) {
this.listAppPrices.splice(index, 1);
};
});
I kind of having the idea of how this can be done but I just can't think of the code to write it.
P.S. the codes are simple, I just learned it in code school and wanted to created something for fun to educate myself. Thanks in advance people
angular.module("stack", [])
.controller("FeaturesController", function($scope) {
// this.apps = features;
this.listAppPrices = [];
this.apps = [{ "name": "a1", "price": "12" }, { "name": "a2", "price": "13" }, { "name": "a3", "price": "14" }];
$scope.dummyArray = [];
var f = 0,
x = 0,
rem = false;
this.setSelected = function(app, index) {
console.log("app ", app);
//remove an item
if (app.selected) {
console.log(" list ", $scope.dummyArray);
$scope.dummyArray.forEach(function(e, ind) {
if (e.name === app.name) {
console.log(ind, " e ", e);
rem = true;
$scope.dummyArray.splice(ind, 1);
}
});
console.log("dumm ", $scope.dummyArray);
this.listAppPrices = $scope.dummyArray;
} else {
rem = false;
}
//used to select a div and change its colour
app.selected ? app.selected = false : app.selected = true;
//add an item
if (!rem) {
if ($scope.dummyArray.length) {
$scope.dummyArray.forEach(function(each) {
console.log("each ");
if (each.name !== app.name) {
console.log("inside if ");
f = 1;
}
});
} else {
console.log("inside else ");
$scope.dummyArray.push(app);
}
if (f === 1) {
f = 0;
console.log("push");
$scope.dummyArray.push(app);
}
console.log(" list--> ", $scope.dummyArray.length);
this.listAppPrices = $scope.dummyArray;
}
}
});
.selected {
background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="stack">
<head>
<title>stack</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="panel-heading" ng-controller="FeaturesController as featuresCtrl">
<h1 class="text-center x">App Features</h1>
<div class="text-center">
<div ng-repeat="app in featuresCtrl.apps track by $index" class="btn btn-primary platform-btn-style" ng-click="featuresCtrl.setSelected(app,$index)" ng-class="{selected: app.selected}">{{ app.name }}</div>
<!-- <div ng-if="(c%2===0)" ng-repeat="app in featuresCtrl.apps" class="btn btn-primary platform-btn-style" ng-click="featuresCtrl.setSelected(app)">{{ app.name }}</div> -->
<br>
</div>
<div>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Device Added</th>
<th>Device Price</th>
<th></th>
</tr>
</thead>
<tr ng-repeat="appList in featuresCtrl.listAppPrices">
<td>{{ appList.name }}</td>
<td>{{ appList.price }}</td>
<td>
<button class="btn btn-default" ng-click="featuresCtrl.remove($index)">Remove</button>
</td>
</tr>
</table>
<div>Total : {{ featuresCtrl.totalAppPrice() }}</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
<script type="text/javascript" src="controller.js"></script>
</body>
</html>
I haven't added the functionality of remove button.I also haven't count the totalAppPrice. Otherwise your problem is solved :) .

Angular Error - ReferenceError: $modal is not defined

I am using code form a tutorial and modifying it a bit. I have run into an issue with the edit feature. I keep getting a "ReferenceError: $modal is not defined" here is my code.
postCtrl:
app.filter('startFrom', function() {
return function(input, start) {
if(input) {
start = +start; //parse to int
return input.slice(start);
}
return [];
}
});
app.filter('dateToISO', function() {
return function(input) {
input = new Date(input).toISOString();
return input;
};
});
app.controller('postsCtrl', function ($scope, $log, $http, $timeout, Data) {
Data.get('posts').then(function(data){
$scope.posts = data.data;
$scope.currentPage = 1; //current page
$scope.filteredItems = $scope.posts.length; //Initially for no filter
$scope.totalItems = $scope.posts.length;
$scope.list_pages = [
{
id: '5',
name: '5'
}, {
id: '10',
name: '10'
}, {
id: '20',
name: '20'
}, {
id: '50',
name: '50'
}, {
id: '100',
name: '100'
}
];
$scope.maxSize = 5;
});
$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;
};
$scope.changePostStatus = function(post){
post.approved = (post.approved=="1" ? "0" : "1");
Data.put("posts/"+post.id,{approved:post.approved});
};
$scope.changePostAnnounce = function(post){
post.announce = (post.announce=="1" ? "0" : "1");
Data.put("posts/"+post.id,{announce:post.announce});
};
$scope.trashPost = function(post){
//$log.log(post);
if(confirm("Are you sure to remove the post")){
Data.delete("posts/"+post.id).then(function(result){
$scope.posts = _.without($scope.posts, _.findWhere($scope.posts, {id:post.id}));
});
}
};
$scope.open = function (p,size) {
var modalInstance = $modal.open({
templateUrl: 'views/postsEdit.html',
controller: 'postsEditCtrl',
size: size,
resolve: {
item: function () {
return p;
}
}
});
modalInstance.result.then(function(selectedObject) {
if(selectedObject.save == "insert"){
$scope.posts.push(selectedObject);
$scope.posts = $filter('orderBy')($scope.posts, 'id', 'reverse');
}else if(selectedObject.save == "update"){
p.description = selectedObject.description;
p.price = selectedObject.price;
p.stock = selectedObject.stock;
p.packing = selectedObject.packing;
}
});
};
});
app.controller('postsEditCtrl', function ($scope, $modalInstance, item, Data) {
$scope.post = angular.copy(item);
$scope.cancel = function () {
$modalInstance.dismiss('Close');
};
$scope.title = (item.id > 0) ? 'Edit Post' : 'Add Post';
$scope.buttonText = (item.id > 0) ? 'Update Post' : 'Add New Post';
var original = item;
$scope.isClean = function() {
return angular.equals(original, $scope.post);
}
$scope.saveProduct = function (post) {
post.uid = $scope.uid;
if(post.id > 0){
Data.put('posts/'+post.id, post).then(function (result) {
if(result.status != 'error'){
var x = angular.copy(post);
x.save = 'update';
$modalInstance.close(x);
}else{
console.log(result);
}
});
}else{
post.status = 'Active';
Data.post('posts', post).then(function (result) {
if(result.status != 'error'){
var x = angular.copy(post);
x.save = 'insert';
x.id = result.data;
$modalInstance.close(x);
}else{
console.log(result);
}
});
}
};
});
html:
<div class="container">
<div class="row" align="center">
<div class="stats"><i class="fa fa-thumb-tack"></i> Total Posts (<span class="attendStat">{{ totalItems }}</span>)<span class="seperator"> | </span><i class="fa fa-trash-o"></i> Trash (<span class="attendStat">X</span>)</div>
</div>
<div class="row">
<div class="col-md-1">PageSize:
<select ng-model="entryLimit" class="form-control" ng-options="obj.id as obj.name for obj in list_pages" ng-init="entryLimit='10'">
</select>
</div>
<div class="col-md-5"><span class="">Filtered: {{ filtered.length }} of {{ totalItems }} total posts</span>
<input type="text" ng-model="search" ng-change="filter()" placeholder="Filter" class="form-control" />
</div>
<div class="col-md-4 pull-right text-right" ng-show="filteredItems > 0">
<uib-pagination total-items="filteredItems" items-per-page="entryLimit" boundary-link-numbers="true" max-size="maxSize" ng-model="currentPage" class="pagination-sm"></uib-pagination>
</div>
</div>
<br/>
<div class="row">
<div class="table-responsive" ng-show="filteredItems > 0">
<table class="table table-striped table-bordered">
<thead>
<th>Publish Date <a ng-click="sort_by('publishdate');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>GUID <a ng-click="sort_by('guid');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Platform <a ng-click="sort_by('platform');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Link Title <a ng-click="sort_by('title');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Redirect Url (Base) <a ng-click="sort_by('redirect');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Announce <a ng-click="sort_by('announce');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Approve <a ng-click="sort_by('approve');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th></th>
</thead>
<tbody ng-repeat="data in filtered = (posts | filter:search | orderBy : predicate :reverse) | startFrom:(currentPage-1)*entryLimit | limitTo:entryLimit">
<tr>
<td class="posts-publishdate">{{data.publishdate | dateToISO | date:'MMM d, y h:mm a' }}</td>
<td>{{data.guid}}</td>
<td>{{data.platform}}</td>
<td>{{data.title}}</td>
<td>{{data.redirect}}</td>
<td>
<button class="btn btn-sm" ng-class="{1:'btn-success', 0:''}[data.announce]" ng-click="changePostAnnounce(data);">{{data.announce == '1' ? "Active" : "Inactive"}}</button>
</td>
<td>
<button class="btn btn-sm" ng-class="{1:'btn-success', 0:''}[data.approved]" ng-click="changePostStatus(data);">{{data.approved == '1' ? "Active" : "Inactive"}}</button>
</td>
<td style="width:100px">
<div class="btn-group">
<button type="button" class="btn btn-default fa fa-edit" ng-click="open(data);"></button>
<button type="button" class="btn btn-danger fa fa-trash-o" ng-click="trashPost(data);"></button>
</div>
</td>
</tr>
<tr>
<td></td>
<td colspan="8">
<table class="table table-striped table-bordered">
<thead>
<th>Image Url <a ng-click="sort_by('img');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Link Description <a ng-click="sort_by('description');"><i class="glyphicon glyphicon-sort"></i></a></th>
<th>Tweet <a ng-click="sort_by('dynamic_content');"><i class="glyphicon glyphicon-sort"></i></a></th>
</thead>
<tbody>
<tr>
<td><img src="{{data.img}}" width="200"></td>
<td>{{data.description}}</td>
<td>{{data.dynamic_content}}</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-12" ng-show="filteredItems == 0">
<div class="col-md-12">
<h4>No customers found</h4>
</div>
</div>
</div>
</div>
Any help would be much appreciated.
You missed to inject $modal dependency inside postsCtrl controller
app.controller('postsCtrl', function ($scope, $log, $http, $timeout, Data, $modal) {
Make sure you have injected particular dependency before getting
access to it. Assuming you have already added ui.bootstrap module
dependency too.
UPDATE
If you are using latest version of angular ui bootstrap which is 0.14.X would need to inject $uibModal instead of $modal. As they rename all boostrap directive and serviec name prepends with uib prefix.
Same thing will happen with $modalInstance dependency, which need to change to $uibModalInstance

AngularJS's ng-table reload not working

I have been googling and none of the solutions have worked for me. I have an AngularJS page that simply has a small set of data with no paganation or anything and I just want to be able to delete an entry and have the table update. However my call to $scope.tableParams.reload() just doesn't do anything.
Here is my controller:
app.controller('viewVersion', ['$scope', '$filter', '$RestService', 'NgTableParams', '$cookies', '$routeParams', '$q', 'Flash', '$location', function($scope, $RestService, NgTableParams, $cookies, $routeParams, $q, Flash, $location) {
$scope.version = {id:null, version:null, comment:null, states:[]};
$scope.permissions=$cookies.get('permissions');
var promise = $RestService.StateList(); //Get the list of states to use to map state ids to their names (BOI, REQ, etc).
promise.success(function(data) {
$scope.stateList = data;
});
promise.then(function(){
var inprom = $RestService.GetVer($routeParams.verid); //Get the version from the API given the version id.
inprom.success(function(data){
data.forEach(function(ver) {
$scope.version['id'] = ver.id;
$scope.version['version'] =ver.version;
$scope.version['platform'] =ver.platform;
$scope.version['comment'] = ver.comment;
if (ver.state!=null) {
var state_info = _.where($scope.stateList, {state_id:ver.state})[0];
$scope.version.states.push({state:state_info.state_name, state_id:ver.state, launch:ver.launch});
}
});
})
inprom.error(function(errorData) {
$cookies.set('flash_message', "Error getting version with ID "+$routeParams.verid);
});
inprom.then(function() {
$scope.tableParams = new NgTableParams({
sorting: { launch: "desc" }
}, {
counts:[],
total: $scope.version.states.length,
filterDelay: 0,
dataset: angular.copy($scope.version.states)
});
});
});
$scope.delete = function(row) {
_.remove($scope.tableParams.settings().dataset, function(item) {
return row.state_id === item.state_id;
});
$scope.tableParams.total($scope.tableParams.settings().dataset.length);
$scope.tableParams.reload();
};
}]);
And the matching html:
<table ng-table="tableParams" class="table table-bordered table-hover table-condensed editable-table" ng-form="tableForm">
<tr ng-repeat="state in version.states" ng-form="stateForm">
<td title="'State'" sortable="'state'">{{state.state}}</td>
<td title="'Launch Date'" sortable="'launch'" ng-switch="state.isEditing" ng-form="launch">
<span ng-switch-default class="editable-text">{{state.launch | date:'medium':'UTC'}}</span>
<div class="controls" ng-class="stateForm.$invalid ? 'has-error' : ''" ng-switch-when="true">
<input type="text" name="name" ng-model="state.launch" class="editable-input form-control input-sm" required />
<p ng-show="stateForm.$invalid && !stateForm.$pristine" class="help-block">Enter a valid date and time.</p>
</div>
</td>
<td>
<button class="btn btn-primary btn-sm" ng-show="permissions.indexOf('admin') > -1" ng-click="save(state, stateForm)" ng-if="state.isEditing" ng-disabled="stateForm.$pristine || stateForm.$invalid"><span class="glyphicon glyphicon-ok"></span></button>
<button class="btn btn-default btn-sm" ng-show="permissions.indexOf('admin') > -1" ng-click="cancel(state, stateForm)" ng-if="state.isEditing"><span class="glyphicon glyphicon-remove"></span></button>
<button class="btn btn-default btn-sm" ng-show="permissions.indexOf('admin') > -1" ng-click="state.isEditing = true" ng-if="!state.isEditing"><span class="glyphicon glyphicon-pencil"></span></button>
<button class="btn btn-danger btn-sm" ng-show="permissions.indexOf('admin') > -1" ng-click="delete(state)" ng-if="!state.isEditing"><span class="glyphicon glyphicon-trash"></span></button>
</td>
</tr>
</table>
Any help would be very appreciated. Thanks!
Your rows are coming directly from your data,
<tr ng-repeat="state in version.states">
...but your delete function is removing rows from ng-table's copy of the data:
$scope.delete = function(row) {
_.remove($scope.tableParams.settings().dataset, function(item) {
return row.state_id === item.state_id;
});
$scope.tableParams.total($scope.tableParams.settings().dataset.length);
$scope.tableParams.reload();
};
You want to pull your rows from ng-table's copy instead:
<tr ng-repeat="state in $data">
Here is a simplified demo: http://plnkr.co/edit/kuAdN3ToKDZtp338E6Hp?p=preview

AngularJS: table edit data + update server

I have managed to create a table using AngularJS. In this table I show products from my datbase which can be filtered on category or some other keywords. Now the user should be able to alter this data in this table to update the data in the database.
AngularJS
categorieFilter = angular.module("categorieFilter", [])
categorieFilter.controller("catFilter", ["$scope", "store", function($scope, store){
$scope.search = "";
$scope.products = [];
$scope.categories = [];
store.getCategories().then(function(data){
$scope.categories = data;
})
store.getProducts().then(function(data){
$scope.products = data;
})
$scope.filterProductsByCats = function(category){
$scope.search = category;
};
}])
categorieFilter.factory('store', function($http, $q){
function _getCategory (){
var deferred = $q.defer();
$http.get('api/categories').success(function (data) {
deferred.resolve(data);
})
return deferred.promise;
}
function _getProducts (){
var deferred = $q.defer();
var prods = [];
$http.get('api/products').success(function (data) {
for(var i = 0;i<data.length;i++)
{
prods[i] = {name: data[i][0], category: data[i][2], price: data[i][1]};
}
deferred.resolve(prods);
})
return deferred.promise;
}
return {
getCategories: _getCategory,
getProducts : _getProducts
};
});
HTML table
<div ng-app="categorieFilter" ng-cloak="" ng-controller="catFilter">
<div class="input-group">
<input type="text" name="table_search" class="form-control input-sm pull-right" ng-model="search" placeholder="Search"/>
<div class="input-group-btn">
<button class="btn btn-sm btn-default">
<i class="fa fa-search"></i>
</button>
</div>
</div>
<div>
<input type="submit" class="btn btn-success" style="margin:10px; width:30%;" ng-repeat="cat in categories" ng-click="filterProductsByCats(cat.categoryName)" value="{{cat.categoryName}}">
</div>
<table class="table table-hover">
<tr style="background-color:#ddd;">
<th colspan="4" style="text-align:left; font-size:16px;"> Category </th>
<th colspan="4" style="text-align:left; font-size:16px;"> Product </th>
<th colspan="4" style="text-align:left; font-size:16px;"> Price </th>
</tr>
<tr ng-repeat="product in products | filter:search | orderBy: 'category'">
<td colspan="4">{{product.category}}</td>
<td colspan="4">{{product.name}}</td>
<td colspan="4">{{product.price}}</td>
</tr>
</table>
Any ideas or reccomendations to get this done?
A library I like to use to achieve the editing of data, is angular xeditable. http://vitalets.github.io/angular-xeditable/
Then save it by posting it back to the webapi

Angular.js ng-click event not firing

I'm new to Angular JS, and I'm trying to implement a page to display, add, edit and delete objects from a REST API. I have functions to add, edit and delete items bound to ng-click, but the edit and delete events are not firing. The only difference between the add and edit/delete bindings seems to be that the edit/delete ng-clicks are inside an ng-repeat.
JavaScript code:
process_errors = function(rejection) {
// Error processing code
}
var exampleApp = angular.module('exampleApp', ['ngResource']);
exampleApp.factory('Example', ['$resource', function($resource) {
return $resource('/api/v1/example/:example_id', {example_id:'#id'});
}]);
exampleApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.common['X-CSRFToken'] = $.cookie('csrftoken');
}]);
exampleApp.controller('exampleListCtrl', ['$scope', 'Example',
function($scope, Example) {
$scope.examples = Example.query();
$scope.newExample = new Example();
$scope.add = function() {
$scope.newExample.$save().then(function(result){
$scope.examples.push(result);
}).then(function() {
$scope.newExample = new Example();
}, process_errors);
}
$scope.editExample = function(example) {
console.log('editing');
var idx = $scope.examples.indexOf(example);
$scope.examples[idx].$save().then(function(result) {
}, function(rejection) {
process_errors(rejection);
$scope.editMode = true;
});
}
$scope.deleteExample = function(example) {
console.log('deletion');
example.$delete().then(function(){
var idx = $scope.examples.indexOf(example);
$scope.examples.splice(idx, 1);
});
}
}]);
HTML:
<div id="content-container" ng-app="exampleApp">
<table class="table table-striped" ng-controller="exampleListCtrl">
<thead>
<!-- Table headers -->
</thead>
<tbody>
<tr>
<form class="form-inline" role="form">
<td><input type="text" class="form-control" ng-model="newExample.start_date" placeholder="2013-11-25"></input></td>
<!-- more fields in the same format -->
<td><button class="btn btn-primary" ng-click="add()">Add</button></td>
</form>
</tr>
</tbody>
<tbody>
<tr ng-repeat="example in examples">
<form class="form-inline" role="form">
<td>
<span ng-hide="editMode">{{example.start_date}}</span>
<input ng-show="editMode" type="text" class="form-control" ng-model="example.start_date" value="{{example.start_date}}"></input>
</td>
<!-- more fields in the same format -->
<td>
<button ng-hide='editMode' class="btn btn-default" ng-click="editMode = true;">Edit</button>
<button ng-show='editMode' class="btn btn-primary" ng-click="editExample(example); editMode = false">Save</button>
</td>
<td><button class="btn btn-danger" ng-click="deleteExample(example)"><span class="glyphicon glyphicon-remove"></span></td>
</form>
</tr>
<tbody>
</table>
</div>
I've also tried binding the functions to $parent.editExample(example).

Categories

Resources