Pass table data into a method in angular - angularjs

Here is my code:
<body ng-app="intranet_App" ng-controller="myCtrl">
<div class="container">
<div class="modal" id="deleteProject">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body" id="confirmMessage">
Are you sure do you want to delete this project??
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="confirmOk" ng-click="deleteProject(x.Id)">Ok</button>
<button type="button" class="btn btn-default" id="confirmCancel" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
<div class="col-xs-12 margin20 padding table-responsive">
<table class="col-xs-12 table table-hover table-bordered" id="projectList">
<thead class="colorBlue">
<tr><th>Project Name</th><th>Client</th><th>Client Co-ordinator</th><th>Action</th></tr>
</thead>
<tbody id="projectListTBody" >
<tr ng-repeat="x in projectList | filter:ProjectName">
<td>{{ x.ProjectName}}</td>
<td>{{ x.Client}}</td>
<td>{{ x.OnsiteCoordinator}}</td>
<td>
<i class="fa fa-user-plus fa-2x" ng-click="addResource()"></i>
<i class="fa fa-edit fa-2x" ng-click="editProj(x.Id)"></i>
<i class="fa fa-trash fa-2x" data-toggle="modal" data-target="#deleteProject"></i>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
<script>
var app = angular
.module("intranet_App", [])
.controller("myCtrl", function ($scope, $http) {
$scope.projDetails = [];
$http.post('/Project/getProjectsList')
.then(function (response) {
console.log(response)
$scope.projectList = response.data;
})
$scope.deleteProject = function (id) {
alert(id)
}
});
</script>
Here when I click delete icon in a table, I am displaying one bootstrap popup modal.In that modal I need to pass x.Id inside deleteProject method on the on click on ok button.But I am unable to hit the method,how to pass it?

In HTML code, add ng-click to delete button
<i class="fa fa-trash fa-2x" data-toggle="modal" data-target="#deleteProject" ng-click="delete(x.id)"></i>
In controller add following method
$scope.delete = function (id) {
$scope.deleteId = id;
}
Using that in deleteProject method
$scope.deleteProject = function () {
//use $scope.deleteId here
alert($scope.deleteId);
}

You're trying to access the x var outside of the ng-repeat in which it is defined it, so naturally, it won't know what x is. This is why you're getting undefined.
Here's the quickest solution I could come up with, there should be a better way, though:
<i class="fa fa-trash fa-2x"
data-toggle="modal"
data-target="#deleteProject"
ng-click="current = x"></i>
Which will assign the last clicked x into current. Then, you should refer to current inside the modal:
<button type="button"
class="btn btn-default"
id="confirmOk"
ng-click="deleteProject(current.Id)">
Ok
</button>

Related

Angular 2 bootstrap modal pass data

I am newbie on angular 2. I am trying to do simple crud operations. However I have problem with using bootstrap modal. The code below, opens bootstrapmodal but I can't send selected movie on DeleteMovie() method.
<div style="margin: 20px">
<h2>Movies List</h2>
<input type="button" Value="Add Movie" class="btn btn-primary" (click)="AddMovie()"/>
<hr/>
<div class="row">
<div class="col-md-12">
<table class="table table-bordered">
<thead>
<tr>
<th>Movie Name</th>
<th>Genre</th>
<th>Edit</th>
<th>Delete</th>
<th>Delete2</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let mv of movies">
<td>{{mv.MovieName}}</td>
<td>{{mv.MovieGenre}}</td>
<td><a routerLink="/movies/{{mv.movieID}}"><i class="glyphicon glyphicon-edit"></i></a></td>
<td><i class="glyphicon glyphicon-remove clickable" (click)="removeMovie(mv)"></i></td>
<td><i class="glyphicon glyphicon-remove clickable" data-toggle="modal" data-target="#myModal2" data-id="{{mv.MovieName}}" (click)="SelectMovie(mv)"></i></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">Delete Record</h4>
</div>
<div class="modal-body">
Do you want to delete {{selectedMovie.MovieName}}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" (click)="removeMovieV2(selectedMovie)" data-dismiss="modal">Delete</button>
</div>
</div>
</div>
</div>
#Component({
selector: 'movies2',
templateUrl: '/templates/movies.component.html',
providers: [MoviesService]
})
export class MoviesComponent implements OnInit {
isLoading = true;
movies: any = [];
selectedMovie:any={};
constructor(private _moviesService: MoviesService, private router: Router, private notificationService: NotificationService) {
}
ngOnInit() {
this.GetMovies();
}
AddMovie() {
this.router.navigate(['/newmovie']);
}
GetMovies() {
this._moviesService.getMovies().subscribe(p => {
this.movies = p;
});
}
SelectMovie(mv: any) {
this.selectedMovie = mv;
}
removeMovieV2(val: any) {
this._moviesService.deleteMovie(val).subscribe(res => {
this.notificationService.printSuccessMessage(val.MovieName + ' has been deleted.');
this.GetMovies();
}, error => {
this.notificationService.printErrorMessage(error);
});
}
}
I think you need to use attribute binding instead of property binding for boostrap to get the value
attr.data-id="{{mv.MovieName}}"
(only for strings)
or
[attr.data-id]="mv.MovieName"
(also supports objects)

ng-click is not working

I'm stuck with this problem for 2 days and I couldn't locate its core so any help on the matter is really appreciated.
I was creating a form that was inline editable with xeditable and the edit(save/cancel) buttons were working as expected but the DELETE button is not calling the given method from the controller. I tried placing it on other parts in the code both as a button and a link and ng-click was not working both ways! I'm quite new at Angular so any debugging tips on how to solve this kinds of problems are welcome! Thanks in advance!
Here is the code from the app file:
var app = angular.module('app', ["Controllers", "xeditable"])
app.run(function (editableOptions) {
editableOptions.theme = 'bs3';
});
Here is the code for the controller (in different .js file from app.js)
angular.module("Controllers", [])
.controller("controller", ["$scope", "$http", function ($scope, $http) {
$scope.users= {};
//get display data
$http.get("/User/All").success(function (data) {
$scope.users= data;
});
//form methods
$scope.editUser = function (data, id) {
edit_data.UserID = id;
$http.post("/User/Edit", edit_data).success(function () {
angular.extend(data, { id: id });
});
};
$scope.deleteUser = function (index, id) {
$http.post("/User/Delete", id).success(function() {
$scope.users.splice(index, 1);
});
};
}]);
Here is the code from the form:
<container ng-app="app" ng-controller="controller">
<table class="table">
<tr>
<th>
Name
</th>
<th>
Surname
</th>
<th></th>
</tr>
<tr ng-repeat="user in users">
<td>
<span editable-text="user.Name" e-name="Name" e-form="rowform" e-required>
{{user.Name}}
</span>
</td>
<td>
<span editable-text="user.Surname" e-name="Surname" e-form="rowform" e-required>
{{user.Surname}}
</span>
</td>
<td style="white-space: nowrap">
<form editable-form name="rowform" onbeforesave="editUser($data, user.UserID)" ng-show="rowform.$visible" class="form-buttons form-inline" shown="inserted == user">
<button type="submit" ng-disabled="rowform.$waiting" class="btn btn-primary">
save
</button>
<button type="button" ng-disabled="rowform.$waiting" ng-click="rowform.$cancel()" class="btn btn-default">
cancel
</button>
</form>
<div class="buttons" ng-show="!rowform.$visible">
<button type="button" class="btn btn-primary" ng-click="rowform.$show()">edit</button>
<button type="button" class="btn btn-danger" ng-click="deleteUser($index,user.UserID)">delete</button>
</div>
</td>
</tr>

Angular CRUD delete row from modal

I am using a simple CRUD API in MEAN STACK with a delete function
app.delete('/api/users/:user_id', function(req, res) {
users.remove({
_id : req.params.user_id
}, function(err, user) {
if (err)
res.send(err);
users.find(function(err, users) {
if (err)
res.send(err)
res.json(users);
});
});
});
The controller
var app = angular.module('usersList', []);
app.controller('usersController', function($scope, $http) {
$http.get('/api/users')
.success(function(userData) {
$scope.users = userData;
$scope.length = userData.length;
})
.error(function(data) {
console.log('Error: ' + data);
});
$scope.deleteUser = function(id) {
$http.delete('/api/users/' + id)
.success(function(data) {
$scope.users = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
});
In the HTML file I populate a table as follow with a btn to open modal with corresponding user details by getting the {{$index}}
<body data-ng-controller="usersController">
<table>
<thead>
<tr>
<th>#</th>
<th>ID</th>
<th>Login</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="userData in users" >
<td><input type="checkbox"/></td>
<td>{{ userData._id }}</td>
<td>{{ userData.id_userLogin }}</td>
<td>{{ userData.email }}</td>
<td>
<!-- Button trigger for Delete modal -->
<button type="button" data-toggle="modal" data-target="#deleteModal{{$index}}" data-ng-click="Clear()">
<span class="glyphicon glyphicon-trash"></span>
</button>
<!-- Delete Modal -->
<div class="modal fade" id="deleteModal{{$index}}" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Delete <strong>{{ userData.id_userLogin }}</strong> account</h4>
</div>
<div class="modal-body">
<div class="alert alert-danger" role="alert">Are you sure you want to delete this account?</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-danger" data-ng-click="deleteUser(user._id)">Delete</button>
</div>
</div>
</div>
</div>
</td>
</tr>
</tbody>
</table>
How can I use the API to delete the corresponding user from the modal as following does not work
<button type="button" class="btn btn-danger" data-ng-click="deleteUser(user._id)">Delete</button>
It is important that the modal is not a confirm delete popup but a modal with content from where the delete button will delete the corresponding user. Any help would be appreciated.
Seem like the problem is solved. I'll just post the answer here. The html of the button should be:
<button type="button" class="btn btn-danger" data-ng-click="deleteUser(userData._id)">Delete</button>
<!-- Use userData._id instead of user._id-->

Angularjs xeditable - Save without edit

I am using angular x-editable to edit html table inline. The problem is I need to give the users option to save whatever data is in the table without putting it in edit mode. If I do that, then my scope value is getting wiped out in onaftersave method.
But if I first put the form in edit mode, and then hit save, everything works fine.
Here is the JSFiddle showing the problem: http://jsfiddle.net/0yvhd84o/
HTML:
<div ng-app="app" ng-controller="Ctrl" style="margin: 50px">
<form editable-form name="tableform" onaftersave="saveTable()">
<table class='table table-bordered'>
<tr style="font-weight: bold">
<td>Name</td>
</tr>
<tr>
<td>
<span editable-text="user.name" e-form="tableform" onaftersave="saveTable()">
{{ user.name || 'empty' }}
</span>
</td>
</tr>
</table>
<div class="btn-edit">
<button type="button" class="btn btn-default" ng-show="!tableform.$visible" ng-click="tableform.$show()">
edit
</button>
<button type="submit" ng-disabled="tableform.$waiting" class="btn btn-primary">save</button>
</div>
<div class="btn-form" ng-show="tableform.$visible">
<button type="button" ng-disabled="tableform.$waiting" ng-click="tableform.$cancel()" class="btn btn-default">cancel</button>
</div>
</form>
<br><br>
<div class="row">
Result is: {{result}}
</div>
</div>
AngularJS
var app = angular.module("app", ["xeditable"]);
app.run(function(editableOptions) {
editableOptions.theme = 'bs3';
});
app.controller('Ctrl', function($scope, $filter) {
$scope.user = {
name: 'awesome user',
status: 2
};
$scope.saveTable = function(){
$scope.result = $scope.user.name ;
}
$scope.result = '';
});
Is there a way to achieve this, so that users should not have to enter edit mode if they dont have to make any changes
I was able to figure this out. Here is the solution in case someone else needs it:
You need to add ng-click="tableform.$show()" to save button as well
<button type="submit" ng-disabled="tableform.$waiting" class="btn btn-primary" ng-click="tableform.$show()">save</button>
Working Example: http://jsfiddle.net/9eg11s0o/

ng-click not executing controller function

I have a very simple function in one of my angular controllers
$scope.search = function () {
alert("Search");
};
and from my view I have
<button type="button" data-ng-click="search()"><i class="fa fa-search"></i></button>
The function is never executed when the button is clicked, but the rest of the code in my controller is executed as expected. Is there any reason why the ng-click directive will not fire my function?
I have similar controllers all working as expected.
Update
The button is within a bootstrap 3 modal, when the button is moved out of the modal, the click event works. Any reason for this happening?
Update
The button is within scope of the controller, here is my controller and view for clarity
(function () {
var module = angular.module("crest");
var brokerGridController = function ($scope, readEndpoint, readBroker) {
$scope.endpoint = "";
$scope.isBusy = false;
$scope.havebroker = false;
$scope.brokers = [];
$scope.searchCriteria = "";
$scope.exception = "";
var setEndpoint = function (response) {
$scope.endpoint = response.Endpoint;
};
readEndpoint.read("BusinessLogicAPI").then(setEndpoint);
var onSuccess = function (response) {
if (response.Message.MessageType == 1) {
onError();
}
$scope.havebrokers = response.brokers.length > 0;
angular.copy(response.brokers, $scope.brokers);
angular.copy(response.Message.body, $scope.exception);
};
var onError = function () {
$("#errorMessageModal").modal("show");
};
$scope.search = function () {
alert("Search");
};
};
module.controller("brokerGridController", ["$scope", "readEndpoint", "readBroker", brokerGridController]);
}());
and the view
<div data-ng-controller="brokerGridController">
<div>
<div class="col-md-4">
<div class="contacts">
<div class="form-group multiple-form-group input-group">
<div id="searchBrokerDropdown" class="input-group-btn input-group-select">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span class="concept">Broker Name</span> <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li>Broker Name</li>
</ul>
<input type="hidden" class="input-group-select-val" name="contacts['type'][]" value="phone">
</div>
<input type="text" name="contacts['value'][]" class="form-control" data-ng-model="searchPhrase">
<span class="input-group-btn searchButton">
<button type="button" class="btn btn-success btn-add" data-ng-click="$parent.search()"><i class="fa fa-search"></i></button>
</span>
</div>
</div>
</div>
</div>
<div>
<div class="col-md-12">
#Html.Partial("_Loading", new LoadingViewModel() { DisplayText = "Loading brokers..." })
<div data-ng-show="!isBusy && !haveBrokers">
<h3>No brokers found.</h3>
</div>
<div class="panel" data-ng-show="!isBusy && haveBrokers">
<div class="panel-heading">
<h4 class="panel-title">Brokers</h4>
<div class="pull-right">
<span class="clickable filter" data-toggle="tooltip" title="Filter Brokers" data-container="body">
<i class="fa fa-filter"></i>
</span>
</div>
</div>
<div class="panel-body">
<input type="text" class="form-control" id="task-table-filter" data-action="filter" data-filters="#task-table" placeholder="Filter Tasks" />
</div>
<table class="table table-hover" id="task-table">
<thead>
<tr>
<th>Broker Name</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="broker in brokers">
<td>{{ broker.Name }}</td>
<td data-ng-show="searchCriteria != 'PolicyNumberLike'"><i class="fa fa-search"></i> View Policies</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
You have to check 2 things in that situation:
Check if your button is in the front (rise his z-index or check is :hover is working), maybe it is not on top so it can't be clickable.
Check if that buttont dont have own $scope (it is crated in subdirective, or in ng-repeat for example), in taht situation check:
<button type="button" data-ng-click="$parent.search()"><i class="fa fa-search"></i></button>
If that 2 things dosen't work check if any command ex. console.log('test_mode') will fire after click.
It's most likely that the button is outside of controller scope, if you provide model with a specific controller you should put search function inside said controller, if you want to keep it in parent controller specify it like this:
$scope.modalFunctions = {
search: function () {
//do something
}
}
then use ng-click="modalFunctions.search"
Ok, I finally found the problem. My angular view is within a bootstrap wizard component (within a bootstrap modal) that I copied from Bootsnipp. The problem was with the javascript that was supplied,
wizardContent.html(currStep.html());
this piece of code replaced the wizard content with the HTML of the correct step. I modified the javascript to hide and show the correct steps instead of copying the HTML of the correct step to the div displayed to the user, which resolved the issue.

Resources