passing a string argument into angularjs ng-click function - javascript

Not sure how to do this, but I would like to pass a string as an argument into ng-click and then us it as a conditional in the function. so something like this?
<div class="row">
<div class="col-md-12 text-center mb-5">
<div class="btn-group">
<button class="btn btn-primary" ng-click=""><span class="ion-plus-circled mr-2"></span>New</button>
<button class="btn btn-outline-primary" ng-click="filter_emails('inbox')"><span class="ion-archive mr-2"></span>Inbox</button>
<button class="btn btn-outline-primary" ng-click=""><span class="ion-paper-airplane align-middle mr-2"></span>Shielded</button>
</div>
</div>
</div>
and then in my controller:
$scope.filter_emails = function(category) {
if (category == "inbox") {
$scope.grouped = group(inbox($scope.emails));
}
else {
$scope.grouped = group($scope.emails);
}
}
This is not working or I obviously wouldn't be posting the question, so what would the correct approach to this?

If you want to pass a string enclose it within quotes
ng-click="filter_emails('inbox')"

Related

How to change click event of button according to different situations on Angular 9

I use Angular 9 to develop a web application. So I need to use Bootstrap Modals
like as
<div class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{MODAL_TITLE}}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>{{MODAL_BODY}}</p>
</div>
<div class="modal-footer">
<button type="button" (click)="function_1()" class="btn btn-primary">SUBMIT</button>
</div>
</div>
</div>
</div>
I called a function when I clicked the Submit button. Well, I just want to change the function that submit function called in different cases.
So the thing that I just want to do in ts file:
MODAL_BODY = "BODY STRING";
MODAL_TITLE: FUNCTION ;
modal.show();
function1(){
console.log("function 1 works"}
}
function2(){
console.log("function 2 works")
}
I want to use function2() instead of function1() sometimes.
Then I want to change function that submit button called in different situations just like as:
<button type="button" (click)="function_1()" class="btn btn-primary">SUBMIT</button>
//some times i need to use this button below. so I need to change it from ts file
<button type="button" (click)="function_2()" class="btn btn-primary">SUBMIT</button>
Is there anyway to do that? from ts file or dynamically?
Thanks in advance.
If we want to change dynamically the button itself in the template the *ngIf structural directive can be used. (As chrnx writes in the question comment.)
To have an example for this take a look at the example below.
In Angular template code:
<p>
Used button
<br />
<button *ngIf="displayedButton === 1" (click)="onButtonOneClick()">
ButtonOne
</button>
<button *ngIf="displayedButton === 2" (click)="onButtonTwoClick()">
ButtonTwo
</button>
</p>
<p>
Change button state
<br />
<button (click)="onChangeStateClick()">Change</button>
</p>
In component code:
import { Component } from "#angular/core";
#Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
displayedButton = 1;
onButtonOneClick() {
console.log("Button 1 click");
}
onButtonTwoClick() {
console.log("Button 2 click");
}
onChangeStateClick() {
this.displayedButton = this.displayedButton === 1 ? 2 : 1;
}
}
Stackblitz example:
https://stackblitz.com/edit/angular-ivy-irmbkk?file=src/app/app.component.ts

jQuery sort cards with up/down arrows

I am using Bootstrap cards on a page, where I want those cards to be sorted using up and down arrows. Every card has arrows in its header, to move it up or down in the layout. But of course, when it gets moved to the top, the up arrow should be gone, likewise for when it hits the bottom.
I've tried using if statements in this style:
// Result: Is never executed.
if(!$(card).find('.sort-down')) {}
// Result: Is always executed.
if($(card).not(':has(.sort-down)') {}
Where $(card) is the div containing the complete card that is being moved.
For example, my complete "move down" code block.
$(document).on('click', '.sort-down', function(e) {
e.preventDefault();
let card = $(this).closest('.card');
let sort_id = $(card).attr('data-sort');
let next_sort_id = Number(sort_id) + 1;
$('[data-sort]').each(function(index, value) {
if($(value).attr('data-sort') == next_sort_id) {
$(value).after($(card));
$(value).attr('data-sort', sort_id);
$(card).attr('data-sort', next_sort_id);
// Change buttons
if($(card).attr('data-sort') == sortCount - 1) {
$(card).find('.sort-down').remove();
if(!$(card).find('.sort-up')) {
// Insert up arrow
}
} else {
if(!$(card).find('.sort-up')) {
// Insert up arrow
}
if(!$(card).find('.sort-down')) {
// Insert down arrow
}
}
if($(value).attr('data-sort') == 0) {
$(value).find('.sort-up').remove();
if(!$(value).find('.sort-down')) {
// Insert down arrow
}
} else {
if(!$(value).find('.sort-down')) {
// Insert down arrow
}
if(!$(value).find('.sort-up')) {
// Insert up arrow
}
}
return false;
}
});
});
A little bit of the HTML so you can get an idea what classes/attributes my jQuery is selecting.
<div class="card mb-3" data-sort="0">
<div class="card-header">
Tekstveld
<button type="button" class="btn btn-sm btn-primary float-right mr-1 sort-down"><i data-feather="arrow-down" width="16" height="16"></i></button>
</div>
<div class="card-body p-0">
<div id="editor"></div>
</div>
</div>
As I usually overcomplicate things, and get the result of it not even working, I'm hoping you could help me with either a simple or more advanced working solution of getting this done.
Using data-sort attribute as a sorting index could be more useful for "Global" sorting or filtering. Like when we click on one button to sort them all based on that property value.
But here, a less complicated alternative is to use jQuery default methods like : next(),prev(),closest(),insertAfter(),insertBefore()
$( document ).ready(function() {
setButtons();
$(document).on('click', '.sort-down', function(e) {
var cCard = $(this).closest('.card');
var tCard = cCard.next('.card');
cCard.insertAfter(tCard);
setButtons();
resetSort();
});
$(document).on('click', '.sort-up', function(e) {
var cCard = $(this).closest('.card');
var tCard = cCard.prev('.card');
cCard.insertBefore(tCard);
setButtons();
resetSort();
});
function resetSort(){
var i=0;
$('.card').each(function(){
//$(this).data('sort',i);
$(this).attr("data-sort", i);
i++;
});
}
function setButtons(){
$('button').show();
$('.card:first-child button.sort-up').hide();
$('.card:last-child button.sort-down').hide();
}
function resetSort(){
var i=0;
$('.card').each(function(){
//$(this).data('sort',i);
$(this).attr("data-sort", i);
i++;
});
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="card mb-3" data-sort="0">
<div class="card-header">
Tekstveld
<button type="button" class="btn btn-sm btn-primary float-right mr-1 sort-down"><i class="fas fa-caret-down"></i></button>
<button type="button" class="btn btn-sm btn-primary float-right mr-1 sort-up"><i class="fas fa-caret-up"></i></button>
</div>
<div class="card-body p-0">
<div class="editor"></div>
</div>
</div>
<div class="card mb-3" data-sort="1">
<div class="card-header">
Voorbeeld
<button type="button" class="btn btn-sm btn-primary float-right mr-1 sort-down"><i class="fas fa-caret-down"></i></button>
<button type="button" class="btn btn-sm btn-primary float-right mr-1 sort-up"><i class="fas fa-caret-up"></i></button>
</div>
<div class="card-body p-0">
<div class="editor"></div>
</div>
</div>
<div class="card mb-3" data-sort="2">
<div class="card-header">
Lorem ipsum
<button type="button" class="btn btn-sm btn-primary float-right mr-1 sort-down"><i class="fas fa-caret-down"></i></button>
<button type="button" class="btn btn-sm btn-primary float-right mr-1 sort-up"><i class="fas fa-caret-up"></i></button>
</div>
<div class="card-body p-0">
<div class="editor"></div>
</div>
</div>
</div>
[UPDATE] : The setButtons() function would hide the non functional buttons when the div reach the limit.
Notice that I added another function resetSort() to reorder those data-sort values. Just in case, you need it for global sorting.

How to get the id and name of an object on button click and display them in a modal in asp.net view

I have a strongly typed view in which I am looping over some objects from a database and dispaying them in a jumbobox with two buttons in it. When I click one of the buttons I have a modal popping up. I'd like to have somewhere in this modal the name and the id of the corresponding object, but I do not really know how to do this. I am a bit confused where to use c# and where javascript. I am a novice in this, obviously.
Can someone help?
This is the code I have so far. I don't have anything in relation to my question, except the code for the modal :
#model IEnumerable<eksp.Models.WorkRole>
#{
ViewBag.Title = "DisplayListOfRolesUser";
}
<div class="alert alert-warning alert-dismissable">You have exceeded the number of roles you can be focused on. You can 'de-focus' a role on this link.</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var dataJSON;
$(".alert").hide();
//make the script run cuntinuosuly
$.ajax({
type: "POST",
url: '#Url.Action("checkNumRoles", "WorkRoles")',
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
if (data == false) {
$(".alert").show();
$('.btn').addClass('disabled');
//$(".btn").prop('disabled', true);
}
}
function errorFunc() {
alert('error');
}
});
</script>
#foreach (var item in Model)
{
<div class="jumbotron">
<h1>#Html.DisplayFor(modelItem => item.RoleName)</h1>
<p class="lead">#Html.DisplayFor(modelItem => item.RoleDescription)</p>
<p> #Html.ActionLink("Focus on this one!", "addWorkRoleUser", new { id = item.WorkRoleId }, new { #class = "btn btn-primary btn-lg" })</p>
<p> <button type="button" class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">Had role in the past</button> </p>
</div>
}
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">#Html.DisplayFor(modelItem => item.RoleName)//doesn't work</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Save</button>
</div>
</div>
</div>
</div>
I think your confusing the server side rendering of Razor and the client side rendering of the Modal. The modal cannot access your Model properties as these are rendered server side before providing the page to the user. This is why in your code <h4 class="modal-title">#Html.DisplayFor(modelItem => item.RoleName)//doesn't work</h4> this does not work.
What you want to do is capture the event client side in the browser. Bootstrap allows you to achieve this by allowing you to hook into events of the Modal. What you want to do is hook into the "show" event and in that event capture the data you want from your page and supply that to the Modal. In the "show" event, you have access to the relatedTarget - which is the button that called the modal.
I would go one step further and make things easier by adding what data you need to the button itself as data-xxxx attributes or to DOM elements that can be easily access via JQuery. I have created a sample for you based on what you have shown to give you an idea of how it can be achieved.
Bootply Sample
And if needed... How to specify data attributes in razor
First of all
you will need to remove the data-toggle="modal" and data-target="#myModal" from the button, as we will call it manually from JS and add a class to reference this button later, your final button will be this:
<button type="button" class="btn btn-default btn-lg modal-opener">Had role in the past</button>
Then
In your jumbotron loop, we need to catch the values you want to show later on your modal, we don't want to show it, so we go with hidden inputs:
<input type="hidden" name="ID_OF_MODEL" value="#item.WorkRoleId" />
<input type="hidden" name="NAME_OF_MODEL" value="#item.RoleName" />
For each information you want to show, you create an input referencing the current loop values.
Now you finally show the modal
Your document.ready function will have this new function:
$('.modal-opener').on('click', function(){
var parent = $(this).closest('.jumbotron');
var name = parent.find('input[name="NAME_OF_MODEL"]').val();
var id = parent.find('input[name="ID_OF_MODEL"]').val();
var titleLocation = $('#myModal').find('.modal-title');
titleLocation.text(name);
// for each information you'll have to do like above...
$('#myModal').modal('show');
});
It simply grab those values we placed in hidden inputs.
Your final code
#model IEnumerable<eksp.Models.WorkRole>
#{
ViewBag.Title = "DisplayListOfRolesUser";
}
<div class="alert alert-warning alert-dismissable">You have exceeded the number of roles you can be focused on. You can 'de-focus' a role on this link.</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var dataJSON;
$(".alert").hide();
//make the script run cuntinuosuly
$.ajax({
type: "POST",
url: '#Url.Action("checkNumRoles", "WorkRoles")',
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
if (data == false) {
$(".alert").show();
$('.btn').addClass('disabled');
//$(".btn").prop('disabled', true);
}
}
function errorFunc() {
alert('error');
}
$('.modal-opener').on('click', function(){
var parent = $(this).closest('.jumbotron');
var name = parent.find('input[name="NAME_OF_MODEL"]').val();
var id = parent.find('input[name="ID_OF_MODEL"]').val();
var titleLocation = $('#myModal').find('.modal-title');
titleLocation.text(name);
// for each information you'll have to do like above...
$('#myModal').modal('show');
});
});
</script>
#foreach (var item in Model)
{
<div class="jumbotron">
<input type="hidden" name="ID_OF_MODEL" value="#item.WorkRoleId" />
<input type="hidden" name="NAME_OF_MODEL" value="#item.RoleName" />
<h1>#Html.DisplayFor(modelItem => item.RoleName)</h1>
<p class="lead">#Html.DisplayFor(modelItem => item.RoleDescription)</p>
<p> #Html.ActionLink("Focus on this one!", "addWorkRoleUser", new { id = item.WorkRoleId }, new { #class = "btn btn-primary btn-lg" })</p>
<p> <button type="button" class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">Had role in the past</button> </p>
</div>
}
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">#Html.DisplayFor(modelItem => item.RoleName)//doesn't work</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Save</button>
</div>
</div>
</div>

animation when removing item from a list in angular

Given the following html:
<div class="list-group-item" ng-repeat="sd in dc.sourceDocuments.items">
<div class="btn-group pull-right" role="group">
<button type="button" data-toggle="tooltip" title="open" class="btn btn-default"><span class="fa fa-envelope-o"></span></button>
<button ng-click="dc.markComplete(sd)" type="button" data-toggle="tooltip" title="mark complete" class="btn btn-default"><span class="fa fa-check"></span></button>
</div>
The typescript method markComplete removes an item from the list after a successful post.
public markComplete(document: SourceDocument): void {
this.$service
.markComplete(document.id)
.then(() => this.remove(document));
}
public remove(document: SourceDocument): void {
var index = this.sourceDocuments.items.indexOf(document);
this.sourceDocuments.items.splice(index, 1);
this.$log.log(`removed document id: ${document.id}`);
}
Angular quite correctly and instantly removes the item from the list.
how do I animate the removal to make the item fade out using angular animate

How to add many functions in ONE ng-click?

I've be looking for how to execute this but I can't find anything related so far, :(
I could nest both functions yes but I'm just wondering if this is possible?
I'd like to do this literally:
<td><button class="btn" ng-click="edit($index) open()">Open me!</button></td>
My JS code at the moment:
$scope.open = function () {
$scope.shouldBeOpen = true;
};
$scope.edit = function(index){
var content_1, content_2;
content_1 = $scope.people[index].name;
content_2 = $scope.people[index].age;
console.log(content_1);
};
I'd like to call two functions with just one click, how can I do this in angularJS?
I thought it'd be straight forward like in CSS when you add multiple classes...but it's not :(
You have 2 options :
Create a third method that wrap both methods. Advantage here is that you put less logic in your template.
Otherwise if you want to add 2 calls in ng-click you can add ';' after edit($index) like this
ng-click="edit($index); open()"
See here : http://jsfiddle.net/laguiz/ehTy6/
You can call multiple functions with ';'
ng-click="edit($index); open()"
A lot of people use (click) option so I will share this too.
<button (click)="function1()" (click)="function2()">Button</button>
The standard way to add Multiple functions
<button (click)="removeAt(element.bookId); openDeleteDialog()"> Click Here</button>
or
<button (click)="removeAt(element.bookId)" (click)="openDeleteDialog()"> Click Here</button>
Try this:
Make a collection of functions
Make a function that loops through and executes all the functions in the collection.
Add the function to the html
array = [
function() {},
function() {},
function() {}
]
function loop() {
array.forEach(item) {
item()
}
}
ng - click = "loop()"
Follow the below
ng-click="anyFunction()"
anyFunction() {
// call another function here
anotherFunction();
}
<!-- Button trigger modal -->
<button type="button" (click)="open(content)" style="position: fixed; bottom: 0; right: 130px;"
class="btn col-sm-1 btn-Danger" >
Reject
</button>
<ng-template #content let-modal>
<div class="modal-header">
<h4 class="modal-title" id="modal-basic-title">Profile update</h4>
<button type="button" class="btn-close" aria-label="Close" (click)="modal.dismiss('Cross click')"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label class="bg-danger text-light" for="Reject">Reason For reject</label>
<textarea matInput placeholder=" Reject" [(ngModel)]="asset_note">{{note}}</textarea>
</div>
</div>
<div class="modal-footer">
<!-- -->
<button type="button" class="btn btn-outline-dark" (click)="reject();modal.close('Save click') ">Save</button>
</div>
</ng-template>
**.ts file**
open(content: any) {
this.modalService.open(content, {ariaLabelledBy: 'modal-basic-title'}).result.then((result) => {
this.closeResult = `Closed with: ${result}`;
}, (reason) => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
close()
{
this.getDismissReason(ModalDismissReasons.ESC);
}
Which of the following is best practice (option1 or option2)
<button (click)="removeAt(element.bookId); openDeleteDialog()"> Click Here
<button (click)="removeAt(element.bookId)" (click)="openDeleteDialog()"> Click Here
ng-click "$watch(edit($index), open())"

Categories