Angular Error - ReferenceError: $modal is not defined - javascript

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

Related

how to put css in selected row in angular js?

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>

Angular foreach - null values

I am having an issue where when I try to select multiple devices and add them to a group, the array of selected devices($scope.deviceIDs.push) is not getting the values. Can anyone see the issue or suggest a different method. I used http://www.dotnetawesome.com/2015/12/multiselect-dropdown-with-checkbox-in-angularjs.html as template for the service I built.
Here is the angular code.
var MyApp = angular.module('MyApp', ['ui.bootstrap', 'angularjs-dropdown-multiselect']);
MyApp.controller('GroupsController', ['GroupsService', '$scope', '$log', '$uibModal',
function (GroupsService, $scope, $log, $uibModal) {
$scope.groupSelected = [];
$scope.location = '';
$scope.groupguid = '';
$scope.newGroupName = '';
$scope.devicesNotinGroup = [];
$scope.newGroupAddMember = 'false';
$scope.isCollapsed = false;
$scope.groupSelected.GroupID = 0;
$scope.SelectedDevices = [];
$scope.deviceIDs = [];
$scope.dropdownSetting = {
scrollableHeight: '200px',
scrollable: true,
enableSearch: true
}
// Populate Jobs
GroupsService.GetDeviceList().then(function (d) {
$scope.GroupList = d.data;
console.log(d.data)
}, function (error) {
alert('Error!');
});
$scope.showChilds = function (item) {
$scope.grouplist = [];
item.active = !item.active;
console.log("here item=" + item.GroupName + " active=" + item.GroupName.active);
grouplist = item.SubGroup;
};
$scope.showInfoForGroup = function (item) {
console.log("item = " + item + "Count = " + item.DeviceCount);
GroupsService.GetGroupDeviceInformation(item).then(function (d) {
$scope.groupSelected = d.data.devicegroupitem;
//$scope.devicesNotinGroup = d.data.devicesnotingroup;
angular.forEach(d.data.devicesnotingroup, function (value, index) {
$scope.devicesNotinGroup.push({ label: value.HostName, id: value.HostName });
});
//console.log($scope.devicesNotinGroup)
})
}, function (error) {
console.log("item = " +item + "Count = " + groupSelected.DeviceCount);
};
$scope.DeleteDeviceFromGroup = function (deviceguid, groupguid ) {
console.log("DeviceGuid = " + deviceguid + " GroupGuid = " + groupguid);
GroupsService.DeleteDeviceFromList(deviceguid, groupguid).then(function (d) {
$scope.groupSelected = d.data;
})
}
$scope.AddDeviceToGroup = function (hostname, groupguid) {
GroupsService.AddDeviceToGroup(hostname, groupguid).then(function (d) {
$scope.showInfoForGroup(dt.guid);
//$scope.groupSelected = d.data.devicegroupitem;
//$scope.devicesNotinGroup = d.data.devicesnotingroup;
$scope.newGroupAddMember = 'false';
})
}
$scope.SubmitMultipleDevices = function (groupguid){
$scope.deviceIDs = [];
console.log($scope.SelectedDevices);
angular.forEach($scope.SelectedDevices = function (value) {
$scope.deviceIDs.push({ dname: value.HostName, dguid: groupguid } );
});
console.log('device ids ');
console.log($scope.deviceIDs);
var data = { deviceIDs: deviceIDs };
console.log(data);
angular.toJson(data);
GroupsService.SubmitMultiDevicesToGroup(data)
.success(function () {
})
.error(function (error) {
});
}
$scope.CreateGroup = function (groupID, groupName, newGroupAddMember) {
angular.isUndefinedOrNull = function (groupID) {
return angular.isUndefined(groupID) || groupID === null
}
$scope.GroupList = '';
console.log("check value equals" + groupID)
GroupsService.CreateSubGroup(groupID, groupName, newGroupAddMember).then(function (d) {
$scope.GroupList = d.data;
$scope.newGroupName = '';
$scope.newGroupAddMember = false;
})
}
$scope.DeleteGroup = function (groupID) {
$scope.GroupList = '';
GroupsService.DeleteSubGroup(groupID).then(function (d){
$scope.GroupList = d.data;
$scope.newGroupName = '';
})
}
}])
MyApp.factory('GroupsService', function ($http) { // explained about factory in Part2
var fac = {};
fac.GetDeviceList = function () {
return $http.get('/DeviceGroups/getgrouptree')
}
fac.GetGroupDeviceInformation = function (guid) {
return $http.get('/DeviceGroups/GetGroupDeviceInfo?groupguid=' + guid)
}
fac.DeleteDeviceFromList = function (deviceguid, groupguid) {
return $http.get('/DeviceGroups/DeleteDeviceFromGroup?deviceguid='+ deviceguid + "&groupguid=" + groupguid)
}
fac.AddDeviceToGroup = function (hostname, groupguid) {
return $http.get('/DeviceGroups/AddDeviceToGroup?hostname=' + hostname + "&groupguid=" + groupguid)
}
fac.CreateSubGroup = function (groupID, groupName, newGroupAddMember) {
return $http.get('/DeviceGroups/CreateGroup?GroupID=' + groupID + "&groupName=" + groupName + "&AddMember=" + newGroupAddMember)
}
fac.DeleteSubGroup = function (groupID) {
return $http.get('/DeviceGroups/DeleteGroup?GroupID=' + groupID)
}
fac.SubmitMultiDevicesToGroup = function (data) {
return $http.post('/DeviceGroups/AddMultipleDevicesToGroup', data)
}
return fac;
});
Here is the view code:
#model List<NetworkCafe.Models.DeviceGroup>
#{
ViewBag.Title = "Groups";
}
<style>
#clickable:hover {
cursor: pointer;
}
.body-content{padding-top:50px}
.checkbox{padding:0;margin:0;}
.dropdown-menu{overflow:auto !important;}
.form-group div{display:inline-block; margin-right:10px}
</style>
<link rel="stylesheet" href="../Content/font-awesome.min.css">
<div class="container" style="width:90%" ng-app="MyApp" ng-controller="GroupsController">
<div class="col-lg-3">
<div ng-class="dropdown" class="panel panel-warning">
<div class="panel-heading">
Tree List of Groups
</div>
<div class="panel-body">
<script type="text/ng-template" id="tree-structure">
<span>
<span id="clickable" ng-class="{'glyphicon glyphicon-chevron-up':(!dt.AddMembers) && (!dt.active), 'glyphicon glyphicon-chevron-down':(!dt.AddMembers) && (dt.active), 'childElement':(dt.AddMembers)}" ng-click="showChilds(dt)"></span>
<span id="clickable" ng-click="showInfoForGroup(dt.guid)"> {{dt.GroupName}} </span>
</span>
<ul ng-if="dt.AddMembers">
#*<li>Device Count: {{dt.DeviceCount}}</li>
<li>Total Ports: {{dt.TotalPortCount}}</li>
<li>Open Ports: {{dt.OpenPortCount}}</li>
<li>Reserved Ports: {{dt.ReservedPortCount}}</li>
<li>Percent Used: {{dt.PercentUsed}}</li>*#
#*<li><button ng-click="href"</li>*#
</ul>
<ul style="list-style: none" ng-show="dt.active" class="childElement">
<li ng-repeat="dt in dt.SubGroup" ng-include="'tree-structure'">
</li>
</ul>
</script>
</div>
<ul style="list-style: none" ng-class="list-group-item" class="parentList">
<li ng-repeat="dt in GroupList" ng-include="'tree-structure'" style="list-style: none">
</li>
</ul>
</div>
</div>
<div class="col-lg-3">
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">Group {{groupSelected.GroupName}} Information</h3>
</div>
<div class="panel-body">
<span ng-hide="!groupSelected.AddMembers">
This group has devices and can not have subgroups.
</span>
<table class="table table-striped table-hover" ng-hide="!groupSelected.AddMembers">
<tr>
<td>Device Count: </td>
<td></td>
<td>{{groupSelected.DeviceCount}}</td>
</tr>
<tr>
<td>Total Ports: </td>
<td></td>
<td>{{groupSelected.TotalPortCount}}</td>
</tr>
<tr>
<td>Open Ports: </td>
<td></td>
<td>{{groupSelected.OpenPortCount}}</td>
</tr>
<tr>
<td>Reserved Ports: </td>
<td></td>
<td>{{groupSelected.ReservedPortCount}}</td>
</tr>
<tr>
<td>Percent Used:</td>
<td></td>
<td>{{groupSelected.PercentUsed}}</td>
</tr>
</table>
<span ng-hide="groupSelected.AddMembers">
This group has subgroups and can not have members.<br /><br />
<label>CREATE SUBGROUP</label><br />
<input ng-model="newGroupName" placeholder="Group Name" /><br />
<label>Group Type</label><br />
<input type="checkbox" ng-model="newGroupAddMember" ng-checked="!newGroupAddMember" />Group will be used for Device.<br />
<button type="submit" class="btn btn-success" ng-click="CreateGroup(groupSelected.GroupID, newGroupName, newGroupAddMember)">Submit</button><br />----------------------- <br />
</span>
<span>
<a class="btn btn-danger" ng-click="DeleteGroup(groupSelected.GroupID)">Danger Delete Group </a> <br />
Delete Group. This will delete all subgroups and devices under this group.
</span>
</div>
</div>
</div>
<div class="col-lg-6" ng-hide="!groupSelected.AddMembers">
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">Device List</h3>
</div>
<div class="panel-body">
<table class="table table-striped table-hover ">
<tr>
<th></th>
<th>Device Name</th>
<th>Total Ports</th>
<th>Open Ports</th>
<th>Reserved Ports</th>
<th>Percent Used</th>
</tr>
<tr ng-repeat="dl in groupSelected.DeviceList">
<td> <i id="clickable" class="fa fa-times" ng-click="DeleteDeviceFromGroup(dl.guid, groupSelected.guid)"></i> </td>
<td>{{dl.DeviceName}}</td>
<td>{{dl.TotalPortCount}}</td>
<td>{{dl.OpenPortCount}}</td>
<td>{{dl.ReservedPortCount}}</td>
<td>{{dl.PercentUsed}}</td>
</tr>
<tr>
<td></td>
</tr>
</table>
#*<ul class="nav navbar-nav">
<li class="dropdown">
----------Add Device from Switch List----------<span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li ng-repeat="sl in devicesNotinGroup">
<span>
<i id="clickable" class="fa fa-plus-square" ng-click="AddDeviceToGroup(sl.HostName, groupSelected.guid)"></i> {{sl.HostName}} {{sl.Site}} {{sl.Zone}}
</span>
</li>
</ul>
</li>
</ul>*#
<form class="form-inline" name="myForm" role="form" ng-submit="SubmitMultipleDevices(groupSelected.guid)">
<div class="form-group">
<label>Add Devices to Group: </label>
#* Directive *#
<div ng-dropdown-multiselect="" extra-settings="dropdownSetting" options="devicesNotinGroup" selected-model="SelectedDevices" checkboxes="true"></div>
</div>
<br />
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
#section scripts{
<script src="~/Scripts/angular-1.4.9/ui-bootstrap-tpls-1.1.2.min.js"></script>
<script src="~/Scripts/AngularControllers/DeviceGroupsV2.js"></script>
<script src="~/Scripts/angular-1.4.9/angularjs-dropdown-multiselect.min.js"></script>
<script src="~/Scripts/angular-1.4.9/lodash.js"></script>
}
Your forEach loop is incorrect.
angular.forEach($scope.SelectedDevices = function (value) {
$scope.deviceIDs.push({ dname: value.HostName, dguid: groupguid } );
});
should be :
angular.forEach($scope.SelectedDevices, function (value) {
$scope.deviceIDs.push({ dname: value.HostName, dguid: value.groupguid } );
});

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

Length angular of items in ng-repeat

First, I have this table:
Where you can see, different colours in the column estado. There are 4 different cases. And i Want to count this different cases. For example in this case there are: Active(green): 1, Vodafone(green+logo): 1, Desactive(Red): 1, Pending(orange):1. But it can change depend of the case.
<div class="input-group">
<div> <h>Instalaciones: {{filteredsites.length}}</h> <h>Active: {{}}</h> <h>Vodafone: {{}}</h> <h>Desactive: {{}}</h> <h>Pending: {{}}</h></div>
</div>
<div class="panel-body">
<div class="row">
<div class="col-lg-3">
<div >
<table class="table table-bordered table-hover table-responsive table-striped dataTable no-footer" data-sort-name="name" data-sort-order="desc">
<tr role = "row" class="info text-center">
<th ng-click="order('msisdn')">Número Teléfono</th>
<th ng-click="order('icc')">ICC</th>
<!--th>IMEI</th-->
<th ng-click="order('ActivationStatus')">Estado</th>
<th ng-click="order('sitename')">Instalación</th>
<th ng-click="order('siteaddress')">Dirección</th>
<th ng-click="order('sitecity')">Ciudad</th>
<th ng-click="order('sitezip')">Código Postal</th>
<th ng-click="order('phonedesc')">Modelo Teléfono</th>
</tr>
<tr class=" text-center" ng-repeat-start="object in filteredsites = (objects | filter:searchText | filter:{parentgroupid:selectedgroup||undefined}) | filter:tableFilter| orderBy:predicate:reverse" ng-click="showDetails = ! showDetails" >
<td>{{object.msisdn}}</td>
<td>{{object.icc}}</td>
<!--td>{{object.ActivationStatus}}</td-->
<td><span ng-init="getStatusCount(object.ActivationStatus)" ng-show="object.ActivationStatus=='AC' && object.ContractingMode=='0'" class="fa fa-square fa-3x"style="color:lime"></span><span ng-show="object.ContractingMode=='2' && object.ActivationStatus=='AC' " ><img src="../img/Vodafone_logo.png" width="40" height="40" style="background-color: lime"></span><span ng-show="object.ActivationStatus=='PA'" class="fa fa-square fa-3x"style="color:yellow"></span><span ng-show="object.ActivationStatus=='DE'" class="fa fa-square fa-3x"style="color:red"></span></td>
<td>{{object.sitename}}</td>
<td>{{object.siteaddress}}</td>
<td>{{object.sitecity}}</td>
<td>{{object.sitezip}}</td>
<td><span ng-show="object.phonedesc==''"></span><span ng-show="object.phonedesc=='Desconocido'">Desconocido</span><span></span>{{getPhoneModel(object.phonedesc)}}</td>
</tr>
</table>
</div>
<!-- /.table-responsive -->
</div>
<!-- /.col-lg-4 (nested) -->
<!-- /.col-lg-8 (nested) -->
</div>
And the controller:
var app = angular.module('dashboard', ['ui.bootstrap']);
app.controller('dashboardController', function ($scope, $http, $modal) {
$scope.objects = [];
$scope.grupos = [];
$scope.longitud = [];
$scope.eventos = [];
var URL = "/api/auth/logout";
var URLOperation = "/api/sites";
var URLModel = "http://localhost:81/api/phonelist/";
$scope.getStatusCount= function (status){
// console.log(status);
var active = 0;
active++;
console.log(active);
angular.forEach(status ,function(obj) {
if (obj.status == status) {
console.log(obj.status);
console.log(status);
console.log(active);
active++;
console.log(active);
} });
}
//Funci?n que devuelve las instalaciones de un usuario
$http.get(URLOperation, $scope)
.success(function (data) {
var groups = data;
angular.forEach(groups, function (group) {
var group2 = group;
angular.forEach(group2.sites, function (group3) {
$scope.longitud.push(group3);
$scope.objects.push(group3);
$scope.predicate = 'msisdn';
$scope.reverse = true;
$scope.order = function (predicate) {
$scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
$scope.predicate = predicate;
};
})
});
})
.error(function (data) {
window.alert('Something Wrong...');
});
});
If someone can help me the count the different ActivationStatus cases i will appreciated.
You pretty much had it correct? I worked on your example in plunker and it worked right off the bet?
ng-show="object.ActivationStatus=='AC' && object.ContractingMode=='0'"
Seemed to be working for me.

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

Categories

Resources