How to get data from smart-table plugin? - angularjs

I am trying to adapt the example of how to use a custom plugin with smart-table. See the "Create your own plugin" section of http://lorenzofox3.github.io/smart-table-website/
Here is a screen shot of my web app so far:
The problem I have is that I do not know how to get the items select from the smart-table. The selected items on the smart-table are "Beer" and "Mountain Biking". Here's my app.js file:
var app = angular.module("app", ['smart-table']);
app.directive('csSelect', function () {
return {
require: '^stTable',
template: '<input type="checkbox"/>',
scope: {
row: '=csSelect'
},
link: function (scope, element, attr, ctrl) {
element.bind('change', function (evt) {
scope.$apply(function () {
ctrl.select(scope.row, 'multiple');
});
});
scope.$watch('row.isSelected', function (newValue, oldValue) {
if (newValue === true) {
element.parent().addClass('st-selected');
} else {
element.parent().removeClass('st-selected');
}
});
}
};
});
Here is my controller:
app.controller("vendorCtrl", function($scope,$http) {
$scope.vendor_to_look_for = "";
$scope.newvendor = "";
$scope.newlogo = "";
$scope.vendors_types = [];
$scope.itemsByPage=5;
$http.get("http://192.168.1.115:8080/vendor").then(function(response) {
$scope.all_vendors = response.data;
});
$http.get("http://192.168.1.115:8080/type").then(function(response) {
$scope.all_types = response.data;
});
$scope.submit_vendor = function() {
// alert("add new vendor [" + $scope.newvendor + "]" );
var data = $.param({ vendor_name: $scope.newvendor, vendor_logo: $scope.newlogo, vendors_types: $scope.vendors_types });
$http.post("http://192.168.1.115:8080/vendor/add",
// [{'vendor': $scope.newvendor}],
data,
{headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then(function(response) {
console.log(response);
console.log(response.data);
});
$http.get("http://192.168.1.115:8080/vendor").then(function(response) {
console.log(response);
console.log(response.data);
$scope.all_vendors = response.data;
});
};
});
Update: Here's the pertinent HTML:
<form ng-submit="submit_vendor()">
<table>
<tr><td><label>Vendor name</label></td><td><input type="text" ng-model="newvendor" placeholder="Name"></td></tr>
<tr><td><label>Logourl</label></td><td><input type="text" ng-model="newlogo" placeholder="Url"></td></tr>
</table>
<table st-table="displayedCollection" st-safe-src="all_types" class="table table-striped">
<thead>
<tr>
<th st-sort="type">Select</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in displayedCollection">
<td cs-select="x"></td>
<td>{{x.type}}</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" class="text-center">
<div st-pagination="" st-items-by-page="itemsByPage" st-displayed-pages="7"></div>
</td>
</tr>
</tfoot>
</table>
<button type="submit" class="btn btn-success btn-lg btn-block"><span class="glyphicon glyphicon-flash"></span> Add </button>
</form>
When I click the add button my submit_vendor() function executes but my the vendor_types I pass in my form data is empty. How do I get the items selected in my table into my form data?
Thanks!

I found this https://github.com/vitalets/checklist-model
This makes things a lot easier. I do not need to declare my csSelect directive :)

Related

Controller function not call in Angular module md-data-table

As per documentation of "md-data-table". I have implemented datatable. But function getDesserts is not calling.
Service code is as below
return {
'getPagingData': function (params) {
var defered = $q.defer();
console.log("Get Paging Service...");
pagination.getPagingData(params,function (response) {
defered.resolve(response);
},
function (error) {
defered.reject(error);
});
return defered.promise;
}
}
And Controller code is as below
$scope.selected = [];
$scope.queryy = {
order: 'name',
limit: 5,
page: 1,
className :"Sla"
};
function success(desserts) {
alert("d");
$scope.desserts = desserts;
}
$scope.getDesserts = function () {
alert("d");
//$scope.promise = $nutrition.desserts.get($scope.query, success).$promise;
$scope.promise = pagingService.getPagingDataHttp($scope.queryy, success).$promise;
};
My html code is as below
<!-- exact table from live demo -->
<md-table-container>
<table md-table md-row-select multiple ng-model="selected" md-progress="promise">
<thead md-head md-order="query.order" md-on-reorder="getDesserts">
<tr md-row>
<th md-column md-order-by="nameToLower"><span>Dessert (100g serving)</span></th>
</tr>
</thead>
<tbody md-body>
<tr md-row md-select="dessert" md-select-id="name" md-auto-select ng-repeat="dessert in desserts.data">
<td md-cell>{{dessert.name}}</td>
</tr>
</tbody>
</table>
</md-table-container>
<md-table-pagination md-limit="query.limit" md-limit-options="[5, 10, 15]" md-page="query.page" md-total="{{desserts.count}}" md-on-paginate="getDesserts" md-page-select></md-table-pagination>
After this implementation, getDessert function in controller is not being
called. Kindly guide me

How to display a textbox in place of text in a column in a table on button-click in angularjs

I am trying to create a small angular and php app. I want to display table and be able to edit it by displaying textbox in place of the old text on the click of a button. Can you please help me with the same. Thanks in advance
This is my controller
angular.module('directiveModule').controller('HomeController',['fetchServerData',function (fetchServerData) {
var ctrl = this;
ctrl.stateVal = false;
ctrl.getTableData = function () {
fetchServerData.getStudentsData()
.then(
function (response) {
ctrl.tableData =response.data;
},
function (response) {
console.log(response);
}
)
};
ctrl.init = function () {
ctrl.getTableData();
};
ctrl.init();
ctrl.editPrice = function () {
ctrl.stateVal = true;
};
}]);
This is the controller html
<table class="table table-striped">
<thead>
<tr>
<th>Flowers</th>
<th>Price</th>
<th>Actions</th>
</tr>
</thead>
<tbody ng-repeat="flower in home.tableData">
<tr>
<td>{{flower.name}}</td>
<td click-to-edit price="flower.price" stateVal="home.stateVal"></td>
<td><button><span class="glyphicon glyphicon-pencil" title="Edit Price" ng-click="home.editPrice()"></span></button></td>
</tr>
</tbody>
</table>
I am using a directive to implement the replacement
angular.module('directiveModule').directive('clickToEdit',[function () {
return{
scope: {
price : '=',
stateVal : '='
},
templateUrl: 'templates/directiveTemplates/clickToEdit.html',
restrict : 'EA',
link: function (scope, elem, attrs) {
scope.edit = scope.stateVal;
}
}
}]);
directive html
<div>
<span ng-hide="edit">
{{price}}
</span>
<div ng-show="edit">
<input class="inputText" type="text"/>
<div class="glyphicon glyphicon-ok" ng-click="save()"></div>
<div class="glyphicon glyphicon-remove" ng-click="cancel()"></div>
</div>
</div>
So this is my code, but the textbox does not appear on ng-click of the edit-pencil
Finally this is my json response
[{"name":"Lilies","price":200},{"name":"Carnations","price":200},{"name":"Roses","price":200},{"name":"Orchids","price":200},{"name":"Tulips","price":200}]
Please help me make it work
The following observations need to be corrected in your code
The attribute name stateVal should be state-val
a) You should keep a watch on your scope.stateVal if you want to scope.edit to be effected when click happened.
Or
b) You can use ng-hide="stateVal" in clickToEdit.html instead of ng-hide="edit".
The click event of the button should be called with flower variable inorder to isolate each edit of the row
<!-- HTML -->
<button ng-click="home.editPrice(flower)"><span class="glyphicon glyphicon-pencil" title="Edit Price">Edit</span></button>
/* Controller */
ctrl.editPrice = function (flower) {
flower.stateVal = true;
};
You can find the working code with above mentioned changes made in the following URL
Click here
Or
https://plnkr.co/edit/ve6AAewoKAtuUHWczaDG?p=preview
You have error in :
<td click-to-edit price="flower.price" stateVal="home.stateVal"></td>
property must by lowercase letters with - (snake case):
<td click-to-edit price="flower.price" state-val="home.stateVal"></td>
stateVal - > state-val

Display the result from a http post method only for the row on which the button is clicked on in AngularJS

I'm new to Angular. I'm trying to start/stop a windows service in .Net using AngularJS.
UI has server name, status of the windows service and two buttons to start and stop the service.
On clicking the button, I am passing the server name to the generic start()/stop() which then calls the webmethod on .aspx page.
That webmethod starts/stops the service and returns the the status of the service.
The problem here is, when I click on first start button, the status column is getting updated for both the servers. I'm only expecting the status to be updated on just the row that I clicked on. I think it is just because I am using the same variable {{retData.result}} for displaying the result from the http post results. How can I solve this issue? Thanks for look into it! Let me know if you need any other details.
angular.module('myApp', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']);
angular.module('myApp').controller('AccordionCtrl', function ($scope, $http, $log) {
$scope.status = {
isDevOpen: true,
isTacOpen: false
};
$scope.retData = {};
$scope.retData.Start = function (item, event) {
$scope.$emit('load')
$http.post('sample.aspx/Start', { serverName: item })
.then(function (response, status, headers, config) {
$scope.retData.result = response.data.d;
$log.info(response);
$scope.$emit('unload')
},function (reason) {
$scope.error = reason;
$log.info(reason);
$scope.$emit('unload')
});
}
$scope.retData.Stop = function (item, event) {
$scope.$emit('load')
$http.post('sample.aspx/Stop', { serverName: item })
.then(function (response, status, headers, config) {
$scope.retData.result = response.data.d;
$log.info(response);
$scope.$emit('unload')
}, function (reason) {
$scope.error = reason;
$log.info(reason);
$scope.$emit('unload')
});
}
}).config(function ($httpProvider) {
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.post["Content-Type"] = "application/json; charset=utf-8";
}).controller('spinnerCtrl', ['$scope', function ($scope) {
$scope.$on('load', function () { $scope.loading = true });
$scope.$on('unload', function () { $scope.loading = false });
}]);
<table class="table table-striped table-condensed">
<thead>
<tr>
<th>#</th>
<th>Server</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Server1</td>
<td>{{retData.result}} {{error}}</td>
<td>
<button type="button" class="btn btn-success btn-sm" ng-click="retData.Start('Server1',$event)">Start</button>
<button type="button" class="btn btn-danger btn-sm " ng-click="retData.Stop('Server1',$event)">Stop</button>
</td>
</tr>
<tr>
<th scope="row">2</th>
<td>Server2</td>
<td>{{retData.result}} {{error}}</td>
<td>
<button type="button" class="btn btn-success btn-sm" ng-click="retData.Start('Server2',$event)">Start</button>
<button type="button" class="btn btn-danger btn-sm" ng-click="retData.Stop('Server2',$event)">Stop</button>
</td>
</tr>
UI
enter image description here
Instead of handling the number of servers in the view, you should handle it in the controller. So in your controller you should have something like this after $scope.status:
$scope.servers = [
{ name: 'Server1', status: 'stopped', error: null },
{ name: 'Server2', status: 'stopped', error: null }
];
And then your view will look like this:
<tbody>
<tr ng-repeat="server in servers">
<th scope="row">{{$index+1}}</th>
<td>{{server.name}}</td>
<td>{{server.status}} {{server.error}}</td>
<td>
<button type="button" class="btn btn-success btn-sm" ng-click="start(server,$event)">Start</button>
<button type="button" class="btn btn-danger btn-sm " ng-click="stop(server,$event)">Stop</button>
</td>
</tr>
</tbody>
All left is to change your start and stop functions, to something like this:
$scope.start = function (item, event) {
$scope.$emit('load')
$http.post('sample.aspx/Start', { serverName: item.name })
.then(function (response, status, headers, config) {
item.status = response.data.d;
$log.info(response);
$scope.$emit('unload')
},function (reason) {
item.error = reason;
$log.info(reason);
$scope.$emit('unload')
});
}
You don't need the $scope.retData so you should remove it and just have the start and stop functions in your $scope.
That's about it.
I'm leaving out a lot of current best practices here, since it would be too big of a topic. I'd advice you to look it up on your own though. I can recommend the angular styleguide.

Breaking the ice on angular

I have a view:
<div id="productList" ng-controller="ProductController">
<table class="table table-bordered">
<thead>
<tr>
<th></th>
<th width="100%">Item ID</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in productItems">
<td><input type="checkbox" /></td>
<td><% item.ID %></td>
</tr>
</tbody>
</table>
</div>
I have a controller:
var TestApp = angular.module('TestApp', [], function( $interpolateProvider ) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
TestApp.controller('ProductController', function ( $scope ) {
ProductRepository.GetPaginatedProducts();
$scope.productItems = ProductRepository.Model;
});
I have a model:
var ProductRepository = function ()
{
return {
Model: null,
GetPaginatedProducts: function()
{
$.ajax( {
"url": Test.URL + "/json/products/paginated",
"dataType": "json",
"method": "post",
"success": function( data )
{
ProductRepository.Model = data;
}
} );
},
}
}
When the ajax finished, it updates the ProductRepository.Model data variable which I want the angular controller scope.productItems to work off of.
This is my first time using angular and i think I've missed the point,
Why is the table not updating with the information?
Please see here for sample ajax call http://plnkr.co/edit/5CiC8MWiwo010nwu32he?p=preview
var TestApp = angular.module('plunker', []);
TestApp.factory('ProductRepository', function($http, $q) {
var Model = [];
return {
Model: Model,
GetPaginatedProducts: function() {
var deferred = $q.defer();
$http.get('paginated.json').then(
//sucess
function(result) {
deferred.resolve(result.data)
}
//error
, function() {});
return deferred.promise;
}
};
})
TestApp.controller('ProductController', function($scope, ProductRepository) {
$scope.productItems = [];
ProductRepository.GetPaginatedProducts().then(function(data) {
//success
$scope.productItems = data;
},
//error
function() {
alert("can't get data");
})
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="plunker">
<div id="productList" ng-controller="ProductController">
<table class="table table-bordered">
<thead>
<tr>
<th></th>
<th width="100%">Item ID</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in productItems">
<td>
<input type="checkbox" />
</td>
<td>{{item.ID}}</td>
</tr>
</tbody>
</table>
</div>
</div>
As #tymeJV stated in the comment, you should use $http or $resource (or restangular) to perform the data access. If you are updating values outside of Angular's framework, it has no way of knowing that data has changed. By using something like $http or $resource, Angular is aware when an event has occurred that can change values and automatically checks for updates.
Alternately, you could manually issues an $apply() to essentially handle the digest update manually (ensuring Angular goes through a digest cycle when you've changed values outside of Angular). Take a look at the documentation on $apply() at https://docs.angularjs.org/api/ng/type/$rootScope.Scope .
However, your best bet is to use the Angular approach in the first place and avoid using jQuery for this.

show 2 array through ng-repeat error

i am trying to make a table from 2 arrays in AngularJS one array contains Employees name and other array contain Services Name and rest of the cells contain check boxes but when i do i got error Error: [ngRepeat:dupes]
here is my AngularJS code
var model = angular.module('wizard', ['ngRoute'])
.config(["$routeProvider", function ($routeProvider) {
$routeProvider.when("/m5", {
controller: "model5Controller",
templateUrl: "/templates/m5.html"
});
$routeProvider.otherwise({ redirectTo: '/' });
}]);
var model5Controller = ["$scope", "$http", "$window", function ($scope,
$http, $window) {
$scope.PBA = [];
$scope.SOB = [];
$http.get('/Test/GetPBA').
then(
function (result) {
//success
$scope.PBA = result.data;
},
function () {
//error
});
$http.get('/Test/GetSOB').
then(
function (result) {
//success
$scope.SOB = result.data;
},
function () {
//error
});
$scope.save = function () {
//to be written
};
}];
GetPBA/GetSOB returns JSON type Array of List
both contain properties like Id, Name
here is my html
<div>
<form ng-submit="save()">
<table border="1">
<tr>
<td><strong>Services</strong></td>
<td ng-repeat="e in PBA">{{e.Name}}</td>
</td>
<tr ng-repeat="i in SOB">
<td>{{i.Name}}</td>
<td ng-repeat="e in PBA">
<input type="checkbox" name="{{e.Id}}" />
</td>
</tr>
</table>
</form>
Try this
<tr ng-repeat="i in SOB track by $index">
<td>{{i.Name}}</td>
<td ng-repeat="e in PBA track by $index">
<input type="checkbox" name="{{e.Id}}" />
</td>
</tr>

Resources