Angular Delete row from table using angular services - angularjs

I am trying to delete a table row using angular services, but unfortunately I don't know how to do that. I have to do that using services because I am using several services with the same control.
<script>
var myApp = angular.module("myApp", []);
myApp.service('allCurrentSettingsService', ['$http', '$q', function ($http, $q) {
var allSettings = null;
this.getList = function () {
var def = $q.defer()
if (allSettings) {
def.resolve(allSettings);
} else {
$http.post('GetAllCurrentSettings')
.then(function (response) {
var response = $.parseJSON(response.data)
allSettings = response;
def.resolve(allSettings);
});
}
return def.promise;
}
}]);
myApp.controller('myController', ['$scope', 'allCurrentSettingsService',
function ($scope, allCurrentSettingsService) {
$scope.allSettings = '';
allCurrentSettingsService.getList().then(function (value) {
$scope.allSettings = value;
});
}
]);
</script>'
And this is my HTML:
`
<div ng-controller="myController">
<table border="1">
<tr ng-repeat="setting in allSettings">
<td><input id="Button1" type="button" value="Delete" data-ng-click="DeleteRow(rowValue)" /></td>
<td class="hidden">{{setting.SettingID}}</td>
<td>{{setting.CompanyName}}</td>
<td>{{setting.CustomerName}}</td>
<td>{{setting.DocumentName}}</td>
</tr>
</table>
</div>
`
Delete method from controller:
[HttpPost]
public static void DeleteRecord(int settingID)
{
try
{
using (SqlConnection conn = new SqlConnection(connStringApps))
{
conn.Open();
using (SqlCommand command = new SqlCommand("DeleteCurrentRecord", conn))
{
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.Add("#SettingId", SqlDbType.VarChar).Value = settingID;
command.ExecuteNonQuery();
command.Parameters.Clear();
}
conn.Close();
}
}
catch (Exception ex)
{
Console.Write(ex.ToString());
}
}

Answer Updated
I do not recommend to remove a row from your service, it's better if you do that from controller, but for figure out how can remove a row from service see the example.
To Remove From Controller you just convert the service codes as controller like what you see in sample.
var app = angular.module("app", []);
app.controller("ctrl", function ($scope, service) {
$scope.data = [
{ name: "a" },
{ name: "b" }
];
$scope.deleteRow = function (row) {
$scope.data = service.removeRow(row, $scope.data);
}
$scope.deleteFromController = function (row) {
var indexOf = $scope.data.indexOf(row);
$scope.data.splice(indexOf, 1);
}
});
app.service("service", function ($rootScope) {
this.removeRow = function (row, data) {
var indexOf = data.indexOf(row);
data.splice(indexOf, 1);
return data;
}
});
<!DOCTYPE html>
<html ng-app="app" ng-controller="ctrl">
<head>
<title></title>
</head>
<body>
<h5>click on rows: delete from service</h5>
<table>
<tr ng-repeat="row in data" ng-click="deleteRow(row)">
<td>{{row.name}}</td>
</tr>
</table>
<h5>click on rows: delete from controller</h5>
<table>
<tr ng-repeat="row in data" ng-click="deleteFromController(row)">
<td>{{row.name}}</td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</body>
</html>

From the front end if you want to remove get the index of setting which you want to remove and then use splice.
in the html there has to be an button which initiate the delete operation
your html should be, a rough idea
<tr ng-repeat ="setting in allSettings">
<td>{{setting.SettingID}}</td>
<!-- other items which you wnted to display-->
<!-- put one button for delete and use $index to track the index of item to be removed-->
<td><button ng-click="removeRow($index)">Remove Row</button></td>
</tr>
your controller>>
$scope.removeRoe = function(index){
//splice will remove the setting row and it will get reflected n the view
$scope.allSettings.splice(index,1);
}
FYI
You need not use service, the removing part has to be done in controller. If you need to hit a backend service(post or delete request) that removes the setting then you need to use angular service

Related

How to wait till the execution of angular js controller is completed

I have created two angular js services as given below:-
var app = angular.module("myApp",[]);
app.service('myServices',function(){
var officeMasterData;
//In this function I fetch the sharepoint list as try to store the data in this service.
this.getDataFromSharepoint = function(){
var deferred = $.Deferred();
var context = new SP.ClientContext('siteUrl');
.......
context.executeQueryAsync(function(){
var listItemEnumerator = colListItem.getEnumerator();
officeMasterData = listItemEnumerator;
return deferredA.resolve(listItemEnumerator);
},function(error){
return deferred.reject(error)
});
return deferred.promise();
}
// Another function in the service to get the data which is already stored from the function above.
this.getDataSaved = function(){
return officeMasterData;
}
});
Then create the second service for another purpose.
Following the code for the second service that I have created.
Here I try to store the email Id of the current Logged in user.
app.service('userServices',function(){
var userArray = {};
this.getCurrentUserDetails = function(){
var deferred = $.Deferred();
var context = new SP.ClientContext.get_current();
var web = context.get_web();
currentUser = web.get_currentUser();
context.load(currentUser);
context.executeQueryAsync(function(){
userArray['id'] = currentUser.get_email();
return deferred.resolve(userArray['id']);
},function(error){
return deferred.reject(error);
});
return deferred.promise();
}
this.getOtherDetails = function(a){
//gets data from another list based on the email Id that has been generated and appends new data to the array.
..........
context.executeQueryAsync(function(){
userArray['First'] = 'Some';
userArray['Last'] = 'thing';
return deferred.resolve(userArray);
},function(error){
return deferred.reject(error);
});
return deferred.promise();
}
this.getMyDetails = function(){
return userArray;
}
});
Then I created two controllers that would consume the services as below:-
angular.module('myApp').controller('userController',userController);
userController.$inject = ['$scope','userServices'];
function userController($scope,userServices){
var alreadySavedData = userServices.getMyDetails();
if(alreadySavedData['First_Name'] === undefined){
var getCurrent = userServices.getCurrentUserDetails();
var getFurtherCurrent = getCurrent.then(function(res){
return userServices.getOtherDetails(res)
});
getFurtherCurrent.then(function(resArr){
$scope.UserDetails = resArr;
$scope.$apply();
});
}else{
var getCurrent = userServices.getMyDetails();
$scope.getCurrent = resArr;
$scope.$apply();
}
}
Here is the code of another controller.
angular.module('myApp').controller('myTController',myTController);
myTController.$inject = ['$scope','myServices','userServices'];
function mTController($scope,myServices,userServices){
var userDetails = userServices.getMyDetails();
var myData = myServices.getDataFromSharepoint();
}
Here is the HTML code for the reference:-
<body data-ng-app="myApp">
<div id="main_header" ng-controller="userController as user">
<div id="header_inner1">
<div class="mobile_menu">
<div class="ham1"></div>
<div class="ham2"></div>
<div class="ham3"></div>
</div>
<div id="logo">
<img src="images/myImg.png" alt="imgLogo"/>
</div>
</div>
</div>
<div ng-controller="mTController" id="myTC" style="display:none;margin-top:10px;">
<table>
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Company Name</th>
</tr>
</thead>
<tr ng-repeat="tr in offices">
<td data-ng-cloak>{{tr.ID}}</td>
<td data-ng-cloak>{{tr.First_x0020_Name}}</td>
<td data-ng-cloak>{{tr.Last_x0020_Name}}</td>
<td data-ng-cloak>{{tr.Company_x0020_Name}}</td>
</tr>
</table>
</div>
<script src="js/userController.js"></script>
<script src="js/officeController.js"></script>
</body>
Here the problem is that my mTController gets executed before userController
Here the I want to execute the mTController after userController is completely executed because the data passing from the userController will be used in mTController for further operations and that's not happening.
What could be the problem?
I have googled around but I couldn't found any solution.
Any help would be appreciable.

Scoping issue on ng-change function on HTML SELECT in AngularJS

I am trying to implement, in a larger context, exactly what is being done in FIDDLE, shown here:
HTML:
<div ng-controller="MyCtrl">
<select
ng-options="ptoGroup as ptoGroup.classname for ptoGroup in ptoGroupTypes"
ng-model="ptoItem"
ng-change="ptoUpdateUserQueryForm1()">
</select>
{{ptoItem.classname}}
</div>
Javascript
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
myApp.controller("MyCtrl", function($scope) {
$scope.ptoGroupTypes = [
{"classname": 'n1'},
{"classname": 'n2'},
{"classname": 'n3'}
];
$scope.ptoUpdateUserQueryForm1 = function() {
console.log("1. new formtype = " + $scope.ptoItem.classname);
};
});
This jsfiddle works great.
In my application, everything works exactly the same way except that inside the $scope.ptoUpdateUserQueryForm function, the value of $scope seems okay but the value of $scope.ptoItem is undefined.
My HTML
<body ng-app="cdu_app">
<div ng-controller="cdu_controller">
<table>
<tr>
<td>Type</td>
<td>
<select
ng-options="ptoGroup as ptoGroup.classname for ptoGroup in ptoGroupTypes"
ng-model="ptoItem"
ng-change="ptoUpdateUserQueryForm()"></select>
</td>
</tr>
<tr>
<td>ptoItem.classname: </td>
<td>{{ ptoItem.classname }}</td>
</tr>
</table>
</div>
</body>
My Javascript
var cduApp = angular.module("cdu_app", []);
cduApp.controller('cdu_controller', function ($scope, $http) {
$scope.ptoGroupTypes = [
{ "classname": "Team" },
{ "classname": "Organization" }
];
$scope.ptoUpdateUserQueryForm = function() {
console.log(" $scope.ptoUpdateUserQueryForm = function()");
console.log("new form type is: " + $scope.ptoItem.classname);
};
});
I am running with Angularjs 1.4.8.
Not sure if that was a type but the object ptoGroupTypes needs to be as
$scope.ptoGroupTypes = [
{ "classname": "Team" },
{ "classname": "Organization" }
];
The closing '}' should be ']'.
Checkout this FIDDLE. It is working.
Just thought of mentioning I changed the name of app from cdu_app to myApp for the sake of Fiddle to work.

Array Push not working with Real Time

I'm using Pusher for Angular Webapp for Real Time Application. I need add to array products a new item when other add a item from form in other session. In my sessiĆ³n it's works. In another session the data obtained if it is added to the array but not shown in the ng-repeat.
Controller:
.controller('MainCtrl', ['$scope','Products',function($scope,Products) {
$scope.products = Products.getAll();
var pusher = new Pusher('MY KEY', {
encrypted: true
});
$scope.addProduct = function(product){
Products.addProduct(product);
}
var callback = function(data) {
$scope.products.push(data.NewProduct);
console.log($scope.products);
};
var channel = pusher.subscribe('products');
channel.bind('addProduct', callback);
}]);
View:
<tbody>
<tr ng-repeat="product in products track by product.id">
<td >{{product.name}}</td>
<td>{{product.unity}}</td>
<td>{{product.price}}</td>
<td>
<button>
Edit
</button>
<button>
Delete
</button>
</td>
</tr>
</tbody>
$evalAsync Executes the expression on the current scope at a later point in time.
So add $evalAsync to callback function in your code
.controller('MainCtrl', ['$scope','$evalAsync','Products',function($scope,$evalAsync, Products) {
$scope.products = Products.getAll();
var pusher = new Pusher('MY KEY', {
encrypted: true
});
$scope.addProduct = function(product){
Products.addProduct(product);
}
var callback = function(data) {
$scope.products.push(data.NewProduct);
console.log($scope.products);
};
var channel = pusher.subscribe('products');
channel.bind('addProduct', $evalAsync(callback));
}]);
I did it like this:
var callback = function(data) {
$scope.$apply(function(){
$scope.products.push(data.Producto);
});
console.log($scope.products);
};

Change the url without reloading the controller in Angularjs

Initially, I am showing all the users name in the table. Once the user selected any one of the name, I call the LoadData method with the selected user as the parameter. I am changing the url #/Trades/User/User1 and append the details under the User1. My requirement is 1) In the LoadData method, I want to change the url to as #/Trades/User/User1 or #/Trades/User/User2 based on the selection 2) It should update the data and reflect in view, but it should not reload the controller.
HTML
<div ng-app="myApp" ng-controller="myCtrl">
<table>
<tr ng-repeat-start="val in data.Titles" class="h" ng-click="LoadData(val.title)">
<td colspan="2" ng-hide="val.title == undefined">{{val.title}}</td>
</tr>
<tr ng-repeat="con in val.details">
<td>{{con.portfolio}}</td>
<td>{{con.status}}</td>
</tr>
<tr ng-repeat-end>
<td colspan="2">Load More</td>
</tr>
</table>
</div>
Code
angular.module("myApp", [])
.controller("myCtrl", ["$scope", function ($scope) {
$scope.data = {"Titles":[{title:"User 1",
details: [{portfolio: "Microsoft", status:"Active"},{portfolio:"IBM", status:"Inactive"}]
}, {title:"User 2",
details: [{portfolio: "Yahoo", status:"Inactive"},{portfolio: "Google", status:"Active"}]
}]};
$scope.LoadData = function(id) {
Change the url as #/Trades/Author/User1
Load the details of the User1
};
});
You could try this. I am using this currently in my project for something very similar. http://joelsaupe.com/programming/angularjs-change-path-without-reloading/
app.run(['$route', '$rootScope', '$location', function ($route, $rootScope, $location) {
var original = $location.path;
$location.path = function (path, reload) {
if (reload === false) {
var lastRoute = $route.current;
var un = $rootScope.$on('$locationChangeSuccess', function () {
$route.current = lastRoute;
un();
});
}
return original.apply($location, [path]);
};
}])

AngularJS with MongoDB, data is pulled from database, but cannot display with ng-repeat

I am trying to get data from the DB and display it using ng-repeat. The getAll function from the factory does the job properly, I get an object with all the data, but it is not displayed properly. In the table I only get the first index, with nothing after it.
If i try with for(i = 0 ; i < DataService.persons.length ; i++), it works fine, but I cannot use it with ng-repeat.
var testReactie = angular.module('testReactie', ['ngRoute']);
testReactie.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'instructiuni.ejs'
})
.when('/form', {
templateUrl : 'form.ejs',
controller : 'formContr'
})
.when('/test', {
templateUrl : 'joc.ejs',
controller : 'gameContr'
})
.when('/stat', {
templateUrl : 'scoruri.ejs',
controller : 'statContr',
resolve: {
postPromise:['DataService', function(DataService){
return DataService.getAll();
}]
}
});
});
testReactie.factory('DataService', ['$http', function($http) {
var o = {
persons:[],
person:{}
};
o.getAll = function(){
return $http.get('/db').success(function(data){
o.persons = data;
});
};
o.create = function() {
return $http.post('/db', o.person).success(function(data){
o.persons.push(data);
});
};
return o;
}]);
testReactie.controller('mainContr',function($scope) {
});
testReactie.controller('statContr',function($scope, DataService) {
});
<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 class="container">
<h2>Scoruri</h2>
<table class="table">
<thead>
<tr>
<th>Nr.</th>
<th>Sex</th>
<th>Varsta</th>
<th>Timp Mediu</th>
</tr>
</thead>
<tbody>
<div ng-repeat = "pers in DataService.persons">
<tr>
<td>{{$index + 1}}</td>
<td>{{pers.sex}}</td>
<td>{{pers.varsta}}</td>
<td>{{pers.timp}}</td>
</tr>
</div>
</tbody>
</table>
</div>
You cannot run a factory as a controller
In your controller do something like
testReactie.controller('mainContr', ['DataService', '$scope', function(DataService, $scope) {
DataService.getAll().then(function(successData){ // a promise helps you do something when it's resolved
$scope.awesomeData = successData;
}
});
Change your factory's get all to be something like
o.getAll = function(){
var promise = $q.defer(); // the $q helps create a promise
return $http.get('/db').success(function(data){
promise.resolve(data); // promise returns data when resolved
});
return promise; // returns a promise
};
your template should be
<div ng-repeat = "pers in awesomeData">
This is because when you have it in your template, it will automatically call $scope.awesomeData. So when you had DataService then it was calling $scope.DataService which was undefined.
I hope this helps.
I fixed the problem. It was from the HTML. I added the ng-repeat directive in a div and it broke the table. After deleting the div and adding the directive in the tag, it worked fine.

Resources