AngularJS No output No errors - angularjs

After many hours I thought my code is running, but I get no output in my table...
Can't find the error...
the console.log($scope.articles) has the full array of articles.
jscode:
(function () {
"use strict";
angular.module("app.tables", []).controller("articlesCtrl", ["$scope", "$http", "$filter",
function ($scope, $http, $filter) {
var init;
$http.get('SOMEURL').success(function (data) {
$scope.articles = data;
console.log($scope.articles);
}).
error(function (data) {
// log error
})
, $scope.searchKeywords = "", $scope.filteredArticles = [], $scope.row = "", $scope.select = function (page) {
if (!$scope.currentPageArticles || !$scope.currentPageArticles.length) { return; }
var end, start;
return start = (page - 1) * $scope.numPerPage, end = start + $scope.numPerPage, $scope.currentPageArticles = $scope.filteredArticles.slice(start, end)
}, $scope.onFilterChange = function () {
return $scope.select(1), $scope.currentPage = 1, $scope.row = ""
}, $scope.onNumPerPageChange = function () {
return $scope.select(1), $scope.currentPage = 1
}, $scope.onOrderChange = function () {
return $scope.select(1), $scope.currentPage = 1
}, $scope.search = function () {
return $scope.filteredArticles = $filter("filter")($scope.articles, $scope.searchKeywords), $scope.onFilterChange()
}, $scope.order = function (rowName) {
return $scope.row !== rowName ? ($scope.row = rowName, $scope.filteredArticles = $filter("orderBy")($scope.articles, rowName), $scope.onOrderChange()) : void 0
}, $scope.numPerPageOpt = [3, 5, 10, 20], $scope.numPerPage = $scope.numPerPageOpt[2], $scope.currentPage = 1, $scope.currentPageArticles = [], (init = function () {
return $scope.search(), $scope.select($scope.currentPage)
})()
}
])}.call(this));
HTML-Code:
<section class="panel panel-default table-dynamic">
<div class="panel-heading"><strong>Artikel</strong></div>
<div class="table-filters">
<div class="row">
<div class="col-sm-4 col-xs-6">
<form>
<input type="text"
placeholder="Search..."
class="form-control"
data-ng-model="searchKeywords"
data-ng-keyup="search()">
</form>
</div>
</div>
</div>
<table class="table table-bordered table-striped table-responsive">
<thead>
<tr>
<th>
<div class="th">
ID
<span class="fa fa-angle-up"
data-ng-click=" order('idArticles') "
data-ng-class="{active: row == 'idArticles'}"></span>
<span class="fa fa-angle-down"
data-ng-click=" order('-idArticles') "
data-ng-class="{active: row == '-idArticles'}"></span>
</div>
</th>
<th>
<div class="th">
Artikelgruppe
<span class="fa fa-angle-up"
data-ng-click=" order('artGroupName') "
data-ng-class="{active: row == 'artGroupName'}"></span>
<span class="fa fa-angle-down"
data-ng-click=" order('-artGroupName') "
data-ng-class="{active: row == '-artGroupName'}"></span>
</div>
</th>
<th>
<div class="th">
Artikelname
<span class="fa fa-angle-up"
data-ng-click=" order('artName') "
data-ng-class="{active: row == 'artName'}"></span>
<span class="fa fa-angle-down"
data-ng-click=" order('-artName') "
data-ng-class="{active: row == '-artName'}"></span>
</div>
</th>
<th>
<div class="th">
Preis
<span class="fa fa-angle-up"
data-ng-click=" order('artPrice') "
data-ng-class="{active: row == 'artPrice'}"></span>
<span class="fa fa-angle-down"
data-ng-click=" order('-artPrice') "
data-ng-class="{active: row == '-artPrice'}"></span>
</div>
</th>
<th>
<div class="th">
EGIS-Artikelnummer
<span class="fa fa-angle-up"
data-ng-click=" order('egisArtId') "
data-ng-class="{active: row == 'egisArtId'}"></span>
<span class="fa fa-angle-down"
data-ng-click=" order('-egisArtId') "
data-ng-class="{active: row == '-egisArtId'}"></span>
</div>
</th>
<th>
<div class="th">
Sichtbarkeit
</div>
</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="articles in currentPageArticles">
<td>{{articles.idArticles}}</td>
<td>{{articles.artGroupName}}</td>
<td>{{articles.artName}}</td>
<td>{{articles.artPrice}}€</td>
<td>{{articles.egisArtId}}</td>
<td class="articles_active text-center">{{articles.active}}</td>
</tr>
</tbody>
</table>
<footer class="table-footer">
<div class="row">
<div class="col-md-6 page-num-info">
<span>
Zeige
<select data-ng-model="numPerPage"
data-ng-options="num for num in numPerPageOpt"
data-ng-change="onNumPerPageChange()">
</select>
Einträge pro Seite
</span>
</div>
<div class="col-md-6 text-right pagination-container">
<pagination class="pagination-sm"
ng-model="currentPage"
total-items="filteredArticles.length"
max-size="4"
ng-change="select(currentPage)"
items-per-page="numPerPage"
rotate="false"
previous-text="‹" next-text="›"
boundary-links="true">
</pagination>
</div>
</div>
</footer>
</section>
Please help.

The problem you had was that you updating the filteredArticles when searching however you not applying the same in the table. Had a fix on it and here is the Working Plunkr
Code Changed:
HTML:
<tr data-ng-repeat="articles in filteredArticles">
<td>{{articles.idArticles}}</td>
<td>{{articles.artGroupName}}</td>
<td>{{articles.artName}}</td>
<td>{{articles.artPrice}}€</td>
<td>{{articles.egisArtId}}</td>
<td class="articles_active text-center">{{articles.active}}</td>
</tr>
JS:
$http.get('data.json').success(function (data) {
$scope.articles = data;
$scope.filteredArticles = data;
console.log($scope.articles);
})

Related

pushed data is not refelcting in a table using angular

the pushed data from the model is not reflecting in the first table. It is there in console. The fiddle link is attached with this please help me on this.
fiddle link ---- http://jsfiddle.net/8MVLJ/2649/
html=========
<script src="https://code.angularjs.org/1.4.9/angular.min.js"></script>
<script src="https://rawgit.com/dwmkerr/angular-modal-service/master/dst/angular-modal-service.js"></script>
<div class="container" ng-app="app" ng-controller="Controller">
<div class="row">
<div class="col-xs-12">
<table class="table table-striped table-bordered">
<thead>
<th>Attribute Name</th>
<th>Attribute Value</th>
</thead>
<tbody>
<tr ng-repeat="newdetail in newDetails">
<td>
<p ng-model="detail">{{newdetail.attrName}} </p>
</td>
<td>
<p ng-model="detailValue">{{newdetail.userAttrValue}} </p>
</td>
</tr>
</tbody>
</table>
<a class="btn btn-default" href ng-click="show()">Select Attribute</a>
<script type="text/ng-template" id="modal.html">
<div class=" ngdialog-messsage modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" ng-click="close('Cancel')" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-xs-12">
<table class="table table-striped table-bordered">
<thead>
<th>
<input type="checkbox" ng-model="allSelected" ng-model-options="{getterSetter: true}">
</th>
<th>Attribute Name</th>
<th>Attribute Value</th>
</thead>
<tbody>
<tr ng-repeat="detail in details">
<td>
<input type="checkbox" ng-model="detail.Selected">
</td>
<td>
<p ng-model="detail">{{detail.attrName}}</p>
</td>
<td>
<select ng-model="detail.user_attr_value" ng-init="detail.user_attr_value=detail.attr_value_Ind.split(',')[0]" class="form-control full-width">
<option ng-repeat="option in detail .attr_value_Ind.split(',')" value="{{option}}">{{option}}</option>
</select>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="modal-footer">
<div class="form-group">
<input type="button" class="btn btn-primary" value="Add Selected" ng-click="add();close('Cancel')">
<input type="button" class="btn btn-danger " ng-click="checkAll(details.length)" value="Clear">
</div>
</div>
</div>
</div>
</div>
</script>
</div>
</div>
</div>
js===================
var app = angular.module('app', ['angularModalService']);
app.controller('Controller', function($scope, $element, ModalService) {
$scope.newDetails = [{
"attrName": "userType",
"userAttrValue": "Customer",
"userOrGroupId": "aaaazzz8522",
}];
$scope.add = function() {
angular.forEach($scope.details, function(detail) {
if (detail.Selected == true) {
$scope.newDetails.push({
'attrName': detail.attrName,
'attrName': detail.user_attr_value
});
$element.modal('hide');
close($scope.newDetails, 500);
console.log("loop", $scope.newDetails);
}
});
};
$scope.show = function() {
ModalService.showModal({
templateUrl: 'modal.html',
controller: "Controller"
}).then(function(modal) {
modal.element.modal();
modal.close.then(function(result) {});
});
};
//=================================================
$scope.close = function(result) {
close(result, 600);
};
$scope.details = [{
"attrName": "region",
"attrType": "USER",
"attr_value_Ind": "CHN-N,CHN-S,CHN-C",
"buId": "DEFAULT",
}];
var getAllSelected = function() {
var selecteddetails = $scope.details.filter(function(detail) {
return detail.Selected;
});
return selecteddetails.length === $scope.details.length;
}
var setAllSelected = function(value) {
angular.forEach($scope.details, function(detail) {
detail.Selected = value;
});
}
$scope.allSelected = function(value) {
if (value !== undefined) {
return setAllSelected(value);
} else {
return getAllSelected();
}
}
$scope.checkAll = function(Count) {
angular.forEach($scope.details, function(details) {
details.Selected = false;
});
};
});
i have updated your fiddle please check and review.http://jsfiddle.net/8MVLJ/2652/
it's not pushing it's value because you have pass scope in your modal controller and set parent scope like this
ModalService.showModal({
templateUrl: 'modal.html',
controller: "Controller",
scope:$scope <-- added here scope
}).then(function(modal) {
modal.element.modal();
modal.close.then(function(result) {});
});
and add $parent to push your value like this
$scope.$parent.newDetails.push({ <-- added $parent here
'attrName': detail.attrName,
'userAttrValue': detail.user_attr_value
});

selecting all the columns which are present in the table per page at a time

This JS file contains the controller which contains the logic of setting up pagination and logic for single selection and multiple selection of the checkbox.
When I am clicking on select all then it is selecting all the possible records irespective how much records are there in the table at that time.For ex if pagination is showing up 10 records per page and user clicks on select all then user should select only those 10 records insted of all the possible records.
angular.module('ControllerModule', [])
.controller('BundleCtrl',['$scope','BundleService',function($scope, BundleService){
console.log("Inside Controller 1");
$scope.ordered_columns = [];
$scope.allItemsSelected = false;
$scope.viewby = 10;
$scope.totalItems = $scope.bundles.length;
$scope.currentPage = 1;
$scope.itemsPerPage = $scope.viewby;
$scope.maxSize = 5; //Number of pager buttons to show
$scope.setPage = function (pageNo) {
$scope.currentPage = pageNo;
};
$scope.pageChanged = function() {
console.log('Page changed to: ' + $scope.currentPage);
};
$scope.setItemsPerPage = function(num) {
$scope.itemsPerPage = num;
$scope.currentPage = 1; //reset to first page
}
$scope.selectEntity = function () {
// If any entity is not checked, then uncheck the "allItemsSelected" checkbox
for (var i = 0; i < $scope.bundles.length(); i++) {
if (!$scope.bundles[i].isChecked) {
$scope.allItemsSelected = false;
return;
}
}
//If not the check the "allItemsSelected" checkbox
alert("after loop");
$scope.allItemsSelected = true;
};
$scope.selectAll = function () {
// Loop through all the entities and set their isChecked property
for (var i = 0; i < $scope.bundles.length; i++) {
$scope.bundles[i].isChecked = $scope.allItemsSelected;
}
};
}]);
HTML
<!-- HTML code for the table which has all the columns with the select boxes-->
<div class="row">
<input id="search" name="q" type="text" size="40" ng-model="search" placeholder="Search (by bundlename, RAG, ID)">
<div class="container-fluid">
<table class="table table-bordered table-striped" style="margin-top:5px">
<thead>
<tr>
<label>
<th>
<input type="checkbox" ng-model="allItemsSelected" ng-change="selectAll()">Select All
</th>
</label>
<th>{{ all_columns[0]}}&nbsp<span ng-if="!custom" ng-click="dataSort('RAGStatus')"><img class="img"
ng-src="resources/images/down-black-arrow.png"> </span>
<span ng-show="custom" ng-click="dataSort('RAGStatus')"><img class="img" ng-src="resources/images/up-black-arrow.png">
</span>
</th>
<th>{{ all_columns[1]}}&nbsp<span ng-if="!custom" ng-click="dataSort('Status')"><img class="img"
ng-src="resources/images/down-black-arrow.png"> </span>
<span ng-show="custom" ng-click="dataSort('Status')"><img class="img" ng-src="resources/images/up-black-arrow.png">
</span>
</th>
<th>{{ all_columns[2]}}&nbsp<span ng-if="!custom" ng-click="dataSort('BundleID')"><img
class="img" ng-src="resources/images/down-black-arrow.png"> </span>
<span ng-show="custom" ng-click="dataSort('BundleID')"><img class="img" ng-src="resources/images/up-black-arrow.png">
</span>
</th>
<th>{{ all_columns[3]}}&nbsp <span ng-if="!custom" ng-click="dataSort('BundleName')"><img
class="img" ng-src="resources/images/down-black-arrow.png"> </span>
<span ng-show="custom" ng-click="dataSort('BundleName')"><img class="img" ng-src="resources/images/up-black-arrow.png">
</span>
</th>
<th>{{ all_columns[4]}}&nbsp<span ng-if="!custom" ng-click="dataSort('ofOrders')"><img
class="img" ng-src="resources/images/down-black-arrow.png"> </span>
<span ng-show="custom" ng-click="dataSort('ofOrders')"><img class="img"
ng-src="resources/images/up-black-arrow.png">
</span>
</th>
<th>{{ all_columns[5]}}&nbsp<span ng-if="!custom" ng-click="dataSort('ofClosedOrders')"><img
class="img" ng-src="resources/images/down-black-arrow.png"> </span>
<span ng-show="custom" ng-click="dataSort('ofClosedOrders')"><img class="img"
ng-src="resources/images/up-black-arrow.png">
</span>
</th>
<th>{{ all_columns[6]}}&nbsp <span ng-if="!custom" ng-click="dataSort('Actions')"><img
class="img" ng-src="resources/images/down-black-arrow.png"> </span>
<span ng-show="custom" ng-click="dataSort('Actions')"><img class="img" ng-src="resources/images/up-black-arrow.png">
</span>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="entity in bundles.slice(((currentPage-1)*itemsPerPage),((currentPage)*itemsPerPage)) | filter : search |orderBy:predicate:reverse" ng-class="{selected: bundles.isChecked}">
<td>
<input type="checkbox" ng-model="bundles[$index].isChecked" ng-change="selectEntity()">
</td>
<td ng-class="entity.RAGStatus"></td>
<td>{{entity.Status}}</td>
<td>{{entity.BundleID}}</td>
<td>{{entity.BundleName}}
</td>
<td>{{entity.ofOrders}}</td>
<td>{{entity.ofClosedOrders}}</td>
<td>
<div class="btn btn-default follow following"><span>{{entity.Actions}}</span>
</div>
<span class="glyphicon glyphicon-bell"></span>
</td>
</tr>
</tbody>
</table>
<span>View
<select name="singleSelect" id="viewPage" ng-model="viewby"
ng-change="setItemsPerPage(viewby)" ng-options="item for item in options1 track by item">
</select> records per page.
<a href="#module2">
<button>New</button>
</a>
</span>
</div>
</div>
<!-- the code ends here which was my html code -->
image contains the view of my table with all the select boxes

Angular overlay (spinner) when we have multiple request

I have below HTML panel and binds to the controller, in the controller I have 4 calls to server to get my data, my question is how can I show spinner or overlay on top of this panel until all the requests to the server are resolved and I can show the data smoothly.
<div class="container-fluid margin10 padding10 myPanel">
<div class="row-fluid name" ng-bind-html="viewData.msg.name"></div>
<div class="row">
<div class="col-md-11">
<div ng-bind-html="'• ' + (viewData.msg.filtersStr | limitTo: 140) + (viewData.msg.filtersStr.length > 140 ? '...' : '')" ng-attr-title="{{viewData.msg.filtersTooltipStr}}"></div>
</div>
</div>
<div class="row top-buffer-margin">
<div class="col-md-4 text-right">
<div class="col-md-8"><span class="font10" translate="msgs.details.confidence"></span>:</div>
<span ng-bind-html="viewData.msg.severity" ng-class="viewData.msg.severityColor" class="font10 col-md-4 confidence-span"></span>
</div>
</div>
<hr>
<table class="table-striped col-md-12 top-buffer-margin">
<thead>
<tr>
<th class="col-md-3"></th>
<th class="col-md-2 text-center" ng-bind-html="'<i>' + ('msgs.details.countColHead' | translate) + '<i>'"></th>
<th class="col-md-4 text-center" ng-bind-html="'<i>' + ('msgs.details.dynamicCalculation' | translate) + '<i>'"></th>
<th class="col-md-3 text-right" ng-bind-html="'<i>' + ('msgs.details.CalculationColHead' | translate) + '<i>'"></th>
</tr>
</thead>
<tbody>
<tr class="">
<td class="col-md-3">
<div><span translate="msgs.details.number1"></span></div>
</td>
<td class="col-md-2 text-center">
<span ng-bind="viewData.msg.number1.dynamicCount "></span>
</td>
<td class="col-md-4 text-center" >
<span ng-bind="viewData.msg.number1.dynamicCalculation "></span>
</td>
<td class="col-md-3 text-right"
ng-bind="(viewData.msg.number1.percentageCalculation > 0 ? '+' : '') + viewData.msg.number1.percentageCalculation + '%'">
</td>
</tr>
<tr class="">
<td class="col-md-3">
<div><span translate="msgs.details.number2"></span></div>
</td>
<td class="col-md-2 text-center">
<span ng-bind="viewData.msg.number2.dynamicCount "></span>
</td>
<td class="col-md-4 text-center">
<span ng-bind="viewData.msg.number2.dynamicCalculation "></span>
</td>
<td class="col-md-3 text-right"
ng-bind="(viewData.msg.number2.percentageCalculation > 0 ? '+' : '') + viewData.msg.number2.percentageCalculation + '%'">
</td>
</tr>
<tr class="">
<td class="col-md-3">
<div><span translate="msgs.details.number3"></span></div>
</td>
<td class="col-md-2 text-center">
<span ng-bind="viewData.msg.number3.dynamicCount "></span>
</td>
<td class="col-md-4 text-center">
<span ng-bind="viewData.msg.number3.dynamicCalculation "></span>
</td>
<td class="col-md-3 text-right"
ng-bind="(viewata.msg.number3.percentageCalculation > 0 ? '+' : '') + viewData.msg.number3.percentageCalculation + '%'">
</td>
</tr>
</tbody>
</table>
</div>
The controller is like this:
(function() {
'use strict';
angular.module('myApp')
.controller('myController', myController);
/** #ngInject */
function myController($scope, BinsResource, msgEvents, appConstants) {
var msg = null;
$scope.viewData = {msg: {}};
var init = function() {
}
var getMsgDetails = function() {
msg = $scope.selectedMsg;
//
$scope.viewData.msg = {
ruleName: msg.ruleName,
date: moment.utc(msg.time).format('YYYY-MM-DD'),
time: moment.utc(msg.time).format('HH:mm'),
severity: msg.severity,
severityColor: msgsService.getSeverityClassColor(msg.severity, appConstants),
number1: buildEventsData(msg, appConstants.measureType.number1),
number2: buildEventsData(msg, appConstants.measureType.number2),
number3: buildEventsData(msg, appConstants.measureType.number3)
};
var params = prepareDataForBinsHttp(msg);
//number1
BinsResource.post('number1', params).then(
function(response) {
var calculationObject = calculateCalculation(response.data.Interval, msg);
$scope.viewData.msg.number1.dynamicCalculation = calculationObject.calculation;
$scope.viewData.msg.number1.dynamicCount = calculationObject.count;
},
function(error) {
//TODO : Display callback error
}
);
//number2
BinsResource.post('number2', params).then(
function(response) {
var calculationObject = calculateCalculation(response.data.Interval, msg);
$scope.viewData.msg.number2.dynamicCalculation = calculationObject.calculation;
$scope.viewData.msg.number2.dynamicCount = calculationObject.count;
},
function(error) {
//TODO : Display callback error
}
);
//number3
BinsResource.post('number3', params).then(
function(response) {
var calculationObject = calculateCalculation(response.data.Interval, msg);
$scope.viewData.msg.number3.dynamicCalculation = calculationObject.calculation;
$scope.viewData.msg.number3.dynamicCount = calculationObject.count;
},
function(error) {
//TODO : Display callback error
}
);
}
//
$scope.subscribe(msgEvents.message._ALERT_ITEM_SELECTED_, function(selectedMsg){
$scope.selectedMsg = selectedMsg;
if(selectedMsg != null){
getMsgDetails();
}
});
init();
};
})();
I want my HTML be blocked until getMsgDetails() does all its calls to server and calculation and was ready to populate the HTML, how can I do this?
I think your best option, is to use the following angular library
https://github.com/McNull/angular-block-ui
It will display a spinner, or a loading message, until all the promises are solved (it is configurable as well)
Demo here:
http://angular-block-ui.nullest.com/#!/

How to delete data inside the list using bootstrap modal?

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>

Adding fields dynamically to JSON array in angular js

I've got two JSON arrays, one for headers and the other for data. I'm handling the headers, and I'm now displaying the data using ng-repeat. working fine. but, i want to add the data dynamically to $scope.data from the view. i've created a button in the last row of the table as 'add row' clicking on it, will fill the last row with input box each for a column. Further from here i'm not finding ways to proceed...since i'm new in angular js.
Please help me.
HTML code and JS is pasted below.
'use strict';
angular.module('mean.system').controller('IndexController', ['$scope', '$http', 'Global','$window',
function($scope, $http,$window) {
$scope.header = [{'field':'first_name', 'displayName':'First name','type':'required'},{'field':'last_name', 'displayName':'Last Name','type':'required'},{'field':'email','displayName':'Email Address','type':'required'}];
$scope.headerAll=[{'field':'first_name', 'displayName':'First name','type':'required'},{'field':'last_name', 'displayName':'Last Name','type':'required'},{'field':'email', 'displayName':'Email','type':'required'},{'field':'isMarried', 'displayName':'marital Status','type':'optional'},{'field':'nick_name', 'displayName':'Nick Name','type':'optional'}]
$scope.optional = [];
$scope.data=[{'first_name':'ruth','last_name':'vick','email':'ruthvick#gmail.com','isMarried':'no','nick_name':'ruthu'},{'first_name':'rahul','last_name':'kumar','email':'rahul#gmail.com','isMarried':'no','nick_name':'rahul'},{'first_name':'vicky','last_name':'gupta','email':'vicky#gmail.com','isMarried':'no','nick_name':'vicky'}]
$scope.headerAll.forEach(function(result){
if (result.type === 'optional') {
$scope.optional.push(result);
}
});
console.log($scope.optional);
$scope.addColumn = function(field){
/*$scope.toPush = {'field':'marital', 'displayName':'married','type':'required'};
$scope.header.push($scope.toPush);*/
$scope.optional.forEach(function(result){
if (result.field === field) {
$scope.header.push(result);
}
});
};
$scope. deleteColumn = function(field,index){
console.log(index);
$scope.optional.forEach(function(result){
console.log(result.field);
if (result.field === field) {
$scope.header.splice(index,1);
}
});
};
$scope.toPoint = function(index){
$scope.index = index;
console.log($scope.index);
};
$scope. editColumn = function(currentField,fieldToEdit,index){
$scope.header.splice($scope.index,1);
$scope.headerAll.forEach(function(result){
if(result.field === fieldToEdit){
$scope.header.splice($scope.index,0,result);
}
});
};
$scope.showAddBtn = 'true';
$scope.addRowButton = function(){
$scope.showInput = 'true';
$scope.showAddBtn = 'false';
};
$scope.cancel = function(){
$scope.showInput = 'false';
$scope.showAddBtn = 'true';
};
$scope.addRow = function(){
$scope.headerAll.forEach(function(result){
var x= result.field;
console.log(x);
$scope.rowObj = {
x : x
};
console.log($scope.rowObj);
});
};
}
]);
<div>
<table class="table table-bordered table-hover">
<thead class="wrapper">
<tr>
<th ng-repeat="data in header">
<div class="col-md-9">{{data.displayName}}</div>
<div class="col-md-1">
<button href="" ng-click="deleteColumn(data.field,$index)"><span class=" glyphicon glyphicon-trash pull-right"> </span></button>
</div>
<div class="dropdown col-md-1" >
<button class="glyphicon glyphicon-pencil dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" ng-click = "toPoint($index);">
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1" ng-repeat="optionalHeader in optional">
<li role="presentation" ng-repeat="dataEdit in headerAll"><a role="menuitem" tabindex="-1" href="" ng-click="editColumn(data.field,dataEdit.field,$index)">{{dataEdit.displayName}}</a></li>
</ul>
</div>
</th>
<th><div class="dropdown" >
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown">
Add Columns
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1" ng-repeat="optionalHeader in optional">
<li role="presentation" ng-repeat="optionalHeader in optional"><a role="menuitem" tabindex="-1" href="" ng-click="addColumn(optionalHeader.field)">{{optionalHeader.displayName}}</a></li>
</ul>
</div>
</th>
</tr>
</thead>
<tbody >
<tr class="active" ng-repeat="row in data">
<td ng-repeat="fields in headerAll">
{{row.fields.field}}
</td>
</tr>
<tr>
<td ng-repeat="fields in header">
<input type="text" ng-show="showInput" ng-model="input"></input>
</td>
<td>
<a href="" style="color:#63822E" ng-click="addRow()">
<h5 ng-show= "showInput"><span class="glyphicon glyphicon-ok" ></span></h5>
</a>
<a href="" style="color:#63822E">
<h5 ng-show= "showInput" ng-click="cancel()"><span class="glyphicon glyphicon-remove" ></span></h5>
</a>
<a href= "" style="color:#63822E" ng-click = "addRowButton()" ng-show = 'showAddBtn'>
<h5 ><span class="glyphicon glyphicon-plus-sign"></span>
Add a new row
</h5>
</a>
</td>
</tr>
</tbody>
</table>
</div>
i want what ever i type in the input box to be pushed in the $scope.data with the corresponding header taken from $scope.headerAll;
Thanks.
Here is an example where every update to the <input> fields directly updates the new object in the data array. The save button only hides the <input> fields. I think a better way is to validate the data in a save function and only push it when the data is correct. Therefore I didn't remove the following lines
//$scope.newObject = {};
//Maybe some validation
//$scope.data.push($scope.newObject);
HTML
<div ng-app ng-controller="Controller">
<table>
<tr>
<th ng-repeat="header in headers">{{header.name}}</th>
</tr>
<tr ng-repeat="row in data">
<td>{{row.firstname}}</td>
<td>{{row.lastname}}</td>
<td>{{row.gender}}</td>
</tr>
<tr ng-show="creatingObject">
<td ng-repeat="header in headers">
<input type="text" ng-model="newObject[header.field]">
</td>
</tr>
<tr>
<td></td>
<td><button ng-show="creatingObject" ng-click="saveRow()">Save</button></td>
<td><button ng-hide="creatingObject" ng-click="addRow()">Add Row</button></td>
</tr>
</table>
</div>
Controller
function Controller($scope) {
$scope.headers = [{ 'field': 'firstname', 'name': 'Firstname' },
{ 'field': 'lastname', 'name': 'Lastname' },
{ 'field': 'gender', 'name': 'Gender' }];
$scope.creatingObject = false;
$scope.data = [{'firstname': 'john', 'lastname': 'Doe', 'gender': 'male'} ];
$scope.addRow = function() {
//$scope.newObject = {};
var length = $scope.data.push({});
$scope.newObject = $scope.data[length - 1] ;
$scope.creatingObject = true;
}
$scope.saveRow = function() {
//Maybe some validation
//$scope.data.push($scope.newObject);
$scope.creatingObject = false;
}
}
Hope that helps.

Resources