How can I create a list of buttons using AngularJS? - html

I have some data which is presented similar to a search system (list of links on different source):
First unit of data Show Detail
Second unit of data Show Detail
...
Each unit of data has id (orderedNumber) and some information which must be hidden by default. Each unit of data has button which shows this information. The button calls a function ShowHide. I have problem because this function doesn't work with several buttons. Information about the unit of data must be shown when I click on the button (data is determined dynamically).
html:
<div ng-repeat="x in results">
{{ x.orderNumber + '. ' + x.namePackage + ' ' + x.size + ' Bytes '}} <a href={{x.link}}>Download</a>
<input type="button" value="Show detail" ng-click="ShowHide(x.orderNumber)" />
<div ng-show = "IsVisible[orderedNumber]">response</div>
</div>
script.js:
$scope.ShowHide = function (orderedNumber) {
//This will hide the DIV by default.
$scope.IsVisible[orderedNumber] = false;
$scope.ShowHide = function (orderedNumber) {
//If DIV is visible it will be hidden and vice versa.
$scope.IsVisible[orderedNumber] = $scope.IsVisible[orderedNumber] ? false : true;
}
};
How can I create a list of buttons using AngularJS?

Just use a property in the var instead of managing an array like this :
ng-click="ShowHide(x)"
ng-show = "x.visible"
$scope.ShowHide = function (item) {
item.visible = !item.visible
};
EDIT : If you don't have any more logic in the Showhide function you also could do this :
ng-click="x.visible = !x.visible"

Related

How to hide a component if there is no result found in Angular

In my Home page, I have a search bar and imported three components. my search bar have the ability to search through them but just wondering how can I hide a particular component if a result in not found in that component and only show a component that have a result.
The problem I have right now is, if search result is only found in Application group component then, the attachment and training component is showing me blank (pls check uploaded image below). I just want to hide the components that don't have the result while user is filtering/searching and just show it back the component when a user cancel the search.
I would be really appreciated if I can get help or suggestion on this.
<!-- attachments -->
<div>
<app-attachment [attachments]="entity.attachments"></app-attachment>
</div>
<!-- appgroups -->
<div *ngFor="let entityGroup of entity.entityGroups">
<app-application-group [entityGroup]="entityGroup" [entity]="entity"></app-application-group>
</div>
<!-- Training and Support -->
<div>
<app-training [entity]="entity"></app-training>
</div>
</div>
ngOnInit(): void {
this.searchText$ = this.searchService.searchText
.asObservable()
.pipe(debounceTime(750), distinctUntilChanged())
.subscribe((value) => {
this.filterValue = value;
this.loadApplication(this.entityType, this.entityId);
});
this.collapse = false;
this.expanded = true;
this.route.url.subscribe((_value) => {
this.entityType = BaseEntity.stringToType(_value[0].path);
this.entityId = Number(_value[1].path);
this.loadApplication(this.entityType, this.entityId);
this.populateMeetups(this.entityId);
});
}
loadApplication(entityType: EntityType, entityId: number): void {
this.color = BaseEntity.color(this.entityType);
if (this.entityType && this.entityId) {
// this.filterValue = null;
this.childrenActive = null;
this.pageSize = 999;
this.childrenActive = true; // We want to bring only active children for things that have tables.
}
this.entityService
.getApplicationDetails(
entityId,
entityType,
this.pageSize,
this.childrenActive,
this.filterValue,
)
.subscribe((entity) => {
this.entity = entity;
this.ancestor = this.entity.channels.get(0);
this.entityGroup = this.entity.entityGroups.filter(
(r) => r.entityType === EntityType.Application,
);
this.entity.attachments = this.entity.attachments.filter((app) => {
return app.name.toLowerCase().includes(this.filterValue.toLowerCase());
});
});
}
click here to view my screenshot
Use *ngIf to remove stuff from the DOM you don't want to show. For example:
<ng-container *ngIf="entity.attachments?.length">
<div>
<app-attachment [attachments]="entity.attachments"></app-attachment>
</div>
</ng-container>
Or hide it with css:
<div [ngClass]="entity.attachments?.length ? 'show' : 'hide'">
<app-attachment [attachments]="entity.attachments"></app-attachment>
</div>
and the css:
.hide {
visibility: hidden;
}
You may want to consider placing the *ngIf inside the child component instead of the parent.
Try to use ngIf by checking the length of the search result instead of creating a new variable. Also use else block to display no result found as shown below
Show result here
No result found .

Appending access code input into URL as utm tag

I'm currently building a landing page with an access code form field.
I'm stuck on finding a way to get the access code entered into a form to be appended as a tag on the url.
Enter "12345" into field and on submit direct to url "www.website.com/?code=12345"
Below is the code I have so far - :
<script>
function btntest_onclick(){
if (document.getElementById('input-code').value == '1234','5678','9809') {
var domain = "http://www.website.com?";
var data = $(this).serialize();
window.location.href = url
}
else {
alert ( 'not found' );
}
};
</script>
<center>
<span class="text-container">
<input type="text" name="accesscode" placeholder="ACCESS CODE" maxlength="10" size="25" id="input-code">
<p>ENTER</p>
</span>
</center>
Any advice on this would be greatly appreciated!
Thanks.
You have a few problems in the code:
The if containing document.getElementById('input-code').value == '1234','5678','9809'. That's not a valid conditional statement in JS. I assume you were trying to test if the value was equal to any of the strings, which can be done using || (A logical "or").
The code was never added to the end of the URL.
You never defined the url variable you were redirecting to.
Here's a commented version that should explain some ways to do this:
function btntest_onclick() {
// First, we assign the value to a variable, just to keep the code tidy
var value = document.getElementById('input-code').value
// Now we compare that variable against each valid option
// if any of these are true, we will progress
if (value === '1234' || value === '5678' || value === '9809') {
// Use a template literal (The ` quotes) to build the new URL
var url = `http://www.website.com?code=${value}`
// This could also be written as:
// var url = "http://www.website.com?code=" + value
// Navigate to your new URL (Replaced with an alert as a demonstration):
alert(url)
// window.location.href = url
} else {
// Otherwise, show the alert
alert('not found')
}
}
<center>
<span class="text-container">
<input type="text" name="accesscode" placeholder="ACCESS CODE" maxlength="10" size="25" id="input-code">
<p>ENTER</p>
</span>
</center>

How to stop refreshing the select box option after pressing OK button

I have created a UI Page in Servicenow below is my simple HTML snipped that creates a Select box and a OK button
Now i selected the select box as Mango and i typed ok, once i click on ok it is setting the value but when i refresh the browser it going to back to previous view. how to keep the same option which user select until user changes it
function validation(){
var value=document.getElementById("selectedValue").value;
if(value=='disabled selected')
{
alert("Please select any value before submitting");
}
else if(value=="1"){
alert("hello this is mango");
}
}
<div class="container">
<div class="row">
<div class="form-group" style="margin-top:12px;">
<select class="form-control" name="selectedValue" id="selectedValue" style="width:150px;">
<option value="disabled selected">Choose your option</option>
<option value="1" >Mango</option>
<option value="2">Orange</option>
<option value="3">Grapes</option>
</select>
<!--<h4 id="number_of_updates" style="display:none"><span class="label label-danger"></span></h4> -->
</div>
<button type="button" class="btn btn-primary" onclick="validation()" style="padding: 0px 8px;">Ok</button>
</div>
</div>
It is working as required, when i refresh the browser it will be set to Choose your option. Can anyone please help me how to save the selected value till it is changed
To achieve the desired result I would use localStorage.
I would set localStorage item inside your validation() function:
function validation(){
var value=document.getElementById("selectedValue").value;
localStorage.setItem('MyValue', value);
if(value=='disabled selected')
{
alert("Please select any value before submitting");
}
else if(value=="1"){
alert("hello this is mango");
}
}
Note, that I'm setting it to selected value from selectList.
Then we need to retrieve this saved value on page load(in case someone refreshes the page):
window.onload = function (){ //function that is called when your page
var selectList = document.getElementById('selectedValue');
var stored = localStorage.getItem('MyValue');
console.log(stored);
if(stored && selectList){
selectList.value = stored //setting saved value to as selected in selectList
}
}
EDIT: Even though localStorage is supported by majority of browsers, its is recommended to check if its accessible. Like if (typeof localStorage !== 'undefined') ...
There's several ways to keep state across refresh. localStorage is obvious choice but maybe an easier solution for your case may be encoding the state in the URL like this (basically the same way web apps keep some of their state).
Insert this code at the end inside validation() function:
history.pushState(null, '', '?val=' + value);
Insert this code after that function:
window.onload = function() {
var params = new URLSearchParams(location.search);
var value = params.get('val') || 'disabled selected';
var select = document.getElementById('selectedValue');
if (select) select.value = value;
}
That's it. Notes: URLSearchParams doesn't work on IE, instead it's not hard to parse the query by hand.

How to create href link inside controller in Angularjs?

I am showing a flash error message if a mobile number is not validated.
Flash message as "Mobile number not validated. click here to validate".
But I want to display the same error message with "click here" as the hyper link which will redirect me to the top of the page.
if (res.json.response.mobilevalidated == false) {
FlashService.Error("Mobile number not validated." + ( click here ) +" to validate", false);
$scope.disabled = function() {
$scope.model.disabled = true;
$scope.title = "Cannot access until mobile number is validated.";
}
} else {
$scope.model.disabled = false;
}
How can I use html tags inside the controller? As my error message is a dynamic one.
Use ng-include.
Js add
$scope.includePath = function () {
`templateUrl="..../your template path"`
};
HTML
<div ng-include="includePath" > New html is here </div>
Here in this case you can use <button> if you want to give click event.
HTML
<div ng-class="{ 'alert': flash, 'alert-success': flash.type === 'success', 'alert-danger': flash.type === 'error', 'selected': hlink}" ng-click = "linking()" ng-if="flash" ng-bind="flash.message" style="margin-top: 20px; ">
</div>
My Controller
if (res.json.response.mobilevalidated == false) {
$scope.linking = function(){
$location.path('/otp');
}
$scope.hlink =" click here";
FlashService.Error("Mobile number not validated." + $scope.hlink +" to validate" , false);
}
What you are looking for can be achieved using $sce that is included in Angular. Take a look at the Documentation here: https://docs.angularjs.org/api/ng/service/$sce
You basically define your HTML string as trusted in the Controller like this: $sce.trustAsHtml(Stackoverflow") and bind it in the template using ng-bind-html like <span ng-bind-html="mySuperCoolLink"></span>.
There is an example in the documentation liked above.
Edit:
Your function FlashService.Error receives an invalid string. You use string concatenation to include your HTML link, however, that only works if your HTML link is stored in a variable. So you have to do one of the following:
A)
FlashService.Error("Mobile number not validated. click here ) to validate", false);
or B)
var link = "( click here )";
FlashService.Error("Mobile number not validated." + link + " to validate", false);
In your provided code, the JS engine will recognise the round brackets as they are valid JS, but not the pointy brackets (I forgot their name...).
Edit 2:
Plunkr: https://plnkr.co/edit/WzzWtnJW98u3e7eTLn2q?p=preview

How to dynamic add new element in Angularjs

I have a ng-repeat to loop my object value to view.
Then I want to have a button to add new blank element to the last of ng-repeat value.
How can I do this in angular?
My data is json object. I tried
In controller
$scope.objs = {'a': 'a', 'b':'b'};
In view
{{Object.keys(objs).length}};
But nothing show in view.
Update
<div ng-repeat="docstep in docs.docsteps" class="docstep">
{{docstep.text}}
</div>
Then I want to get the length of objects so I can .length + 1 in the button click
But I have no idea how to get objects length. Or is there any better idea?
Bind a click handler to the button using ng-click:
<div ng-repeat="docstep in docs.docsteps" class="docstep">
<input type="text" value="{{docstep.text}}">
</div>
<button ng-click="addNew()">Add another input</button>
When this button is clicked. It will add another blank input
<br>Which the new input will be docstep3
This is how your JS should look:
var myApp = angular.module('myApp',[]);
myApp.run(function($rootScope){
$rootScope.docs = {
"docsteps" : {
"docstep1" : {
"text" : "a"
},
"docstep2" : {
"text" : "b"
}
}
}
var c = 2;
$rootScope.addNew = function(){
count++;
$rootScope.docs.docsteps["docstep"+count] = {"text":count}
}
});
NOTE: You should use ng-app to define work area for angular and use controllers to reside the models(docs) and define the behaviour of your view (addNew).
I took your ng-repeat and made it work. Notice I put your object in the $rootScope but you can apply the same object to any scope that your ng-repeat is in.
JS
var myApp = angular.module('myApp',[]);
myApp.run(function($rootScope){
$rootScope.docs={docsteps:[{text:'A'},{text:'B'},{text:'C'}]};
});
JSFIDDLE: http://jsfiddle.net/mac1175/Snn9p/