Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

Visual Studio Hosting - HostForLIFE.eu :: VS Code Auto-Format Code on Save to Simplify Your Processes

clock October 30, 2024 09:27 by author Peter

For any developer, keeping code neat and orderly is essential, but worrying about formatting all the time can interfere with productivity. What if your code could be formatted automatically each time you hit save? This post will discuss a straightforward yet effective feature in Visual Studio Code (VS Code) that handles formatting for you with a single click.

Step-by-Step Guide: Enabling Format on Save
The magic of auto-formatting in VS Code lies in the "Format on Save" feature. Here's how you can enable it.

  • Open Visual Studio Code: Launch VS Code on your system.
  • Navigate to Settings: Click on `File` in the top menu, then select `Preferences` -> `Settings`.
  • Search for Format on Save: In the search bar, type "save" to filter the settings related to saving files. Look for the option labeled Format On Save. Look in the below image.

  • Enable the Feature: Check the box next to "Format On Save" to enable the feature.
    If you haven't selected a default formatter, VS Code will prompt you to choose one when you enable "Format on Save." You can pick from the available formats installed in your environment. For example, if you have Prettier installed, you can select it as your default formatter. Simply choose the one that suits your needs, and VS Code will use it to format your code every time you save.

The Magic of Auto-Formatting
Once you've enabled "Format on Save," you can write code without worrying about the formatting. Whether you're pasting in code snippets, writing redundant code, or simply speeding through a task, VS Code will ensure everything is clean and organized the moment you hit `CTRL+S`.

For example, imagine you write a block of redundant/dirty JavaScript code like this before Save click.

Without manually adjusting spaces or aligning braces or formatting, simply press `CTRL+S`, and VS Code will automatically format it.

See the magic; now, every time you click on save it'll automatically restructure the whole code.

Why Use Format on Save?

  • Consistency: Ensure consistent code style across your project without manual intervention.
  • Time-Saving: Focus more on logic and less on formatting, as VS Code handles the latter for you.
  • Error Reduction: Properly formatted code is easier to read and debug, reducing the likelihood of syntax errors.

Conclusion
With VS Code's "Format on Save" feature, you can keep your code neat and tidy with minimal effort. It’s a small setting that makes a big difference, letting you code faster and smarter. No need for additional tools—just code, save, and let VS Code do the rest. Give it a try, and experience the magic of auto-formatting in your next coding session.

Thanks a Lot, Everyone! Is this guide helpful? Give it a thumbs up and share it with your fellow developers! Your support keeps the tips and tricks coming.
Happy coding!



AngularJS Hosting Europe - HostForLIFE.eu :: Angular Directives 101

clock October 22, 2024 07:36 by author Peter

If you have been working with Angular directives for quite some time now, this article may help you as a refresher; if you are a beginner, this may get you started with Angular directives. We’ll try to break down the concept into its core parts and give easy examples to understand and approach.


Okay, then, let’s try to get started.

What is an Angular Directive?

Angular directives are HTML attributes that extend the behavior or the appearance of a standard HTML element. In other words, we can say that directives are simply instructions to the DOM. That’s why when we apply a directive to an HTML element or even an Angular component, we can add custom behavior or alter its appearance.
The excellent thing is that Angular provides a set of built-in directives that we can use in our components to cover most use cases.
These Angular built-in directives are part of the CommondModule.

So, we need to import CommonModule when we want to use them.

See an example of importing the built-in directives below.
import {NgForOf, NgIf, NgSwitch, NgSwitchCase} from '@angular/common';

For more information, you can check this official documentation https://v17.angular.io/api/common/CommonModule.

Types of Directives

We need to know the types of directives when dealing with Angular.

Let’s see them one by one.

Component Directives

These are directives with an associated template.
That’s why this is the commonly used directive in Angular application development.
Let’s see an example below.
import { Component } from '@angular/core';

@Component({
  selector: 'app-component-directives-sample',
  standalone: true,
  imports: [],
  templateUrl: './component-directives-sample.component.html',
  styleUrl: './component-directives-sample.component.css'
})
export class ComponentDirectivesSampleComponent {

}

From our example above, if you are already familiar with components and how to generate components.
That’s fundamentally it.
Just remember that all components are directives, but not all directives are components.
Components extend the concept of directives by providing a view (template) to render.

Structural Directives

Structural directives are used to manage the elements from the DOM, such as adding or removing elements. If a developer is building dynamic and interactive web applications with Angular, managing the display of elements based on certain conditions or iterating over a collection is essential.

Angular provides three powerful structural directives to handle these scenarios: *ngIf, *ngSwitch, and *ngFor.

Let’s dive into how these directives work and how to use them.
The *ngIf

This directive allows you to conditionally display or remove an element from the DOM based on a boolean expression.
If the condition is evaluated as true, the element is rendered; otherwise, it is removed from the DOM.
See the example below.

app.component.ts
import { Component } from '@angular/core';
import {NgIf} from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [NgIf],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'sampleDirectives';
  showProduct: boolean = true;
  products:Array<any>= [
    { id: 1,
      name: "Intel Core i9-11900K",
      type: "CPU"
    },
    {
      id: 2,
      name: "AMD Ryzen 9 5950X",
      type: "CPU"
    }
  ];
}


app.component.html
<div *ngIf="showProduct">
  <h2 [innerText]="products[0].type"></h2>
  <p [innerText]="products[0].name"></p>
</div>

From our sample code, we have the showProduct set to true and a product array to hold dummy product data.
With this view, we have decided to get the first index item of the products array.
As a result, the HTML view will show the product type and the product name.
See the output below.

The *ngSwitch
As you can see, the *ngIf works excellent for a single condition, while *ngSwitch is more efficient when you need to toggle between multiple options.
It looks almost like a switch-case statement in programming, where you can choose between different elements to render based on an expression.

See the example below.

app.component.ts
import { Component } from '@angular/core';
import {NgForOf, NgIf, NgSwitch, NgSwitchCase} from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [ NgIf, NgSwitch, NgSwitchCase, NgForOf],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'sampleDirectives';
  showProduct: boolean = true;
  products:Array<Product>= [
    { id: 1,
      name: "Intel Core i9-11900K",
      type: "CPU"
    },
    {
      id: 2,
      name: "AMD Ryzen 9 5950X",
      type: "CPU"
    },
    {
      id: 3,
      name: "EVGA SuperNOVA 850 G5",
      type: "Power Supply"
    },
    {
      id: 4,
      name: "G.Skill Ripjaws V Series 32GB",
      type: "Memory"
    }
  ];
  firstProduct: Product;
  secondProduct: Product;
  thirdProduct: Product;

  constructor() {
    this.firstProduct = this.products[0];
    this.secondProduct = this.products[1];
    this.thirdProduct = this.products[2];
  }
}

export class Product {
  id: number = 0;
  name: string = "";
  type: string = "";
}


app.component.html
<div [ngSwitch]="thirdProduct.type">
  <h2 [innerText]="thirdProduct.type"></h2>
  <p [innerText]="thirdProduct.name"></p>
  <p *ngSwitchCase="'CPU'">
    This product is a CPU.
  </p>
  <p *ngSwitchCase="'Memory'">
    This is a RAM (Random Access Memory).
  </p>
  <p *ngSwitchCase="'Power Supply'">
    This is a Power Supply.
  </p>
</div>


As a result, the HTML view will show the product type and the product name.

See the output below.

The *ngFor
I know what you are thinking if you have been dealing with programming. *ngFor is used to repeat an element for each item in a collection. Looks like a loop, right?
From our previous example, we won’t change “app.component.ts.”
We’ll add the *ngFor inside the app.component.html.
Let’s see an example below.

app.component.html
<div>
  <ul>
    <li *ngFor="let product of products">
        <h2 [innerText]="product.name"></h2>
        <p [ngSwitch]="product.type">
          <span *ngSwitchCase="'CPU'">
            This product is a CPU.
          </span>
          <span *ngSwitchCase="'Memory'">
            This is a RAM (Random Access Memory).
          </span>
          <span *ngSwitchCase="'Power Supply'">
            This is a Power Supply.
          </span>
        </p>
    </li>
  </ul>
</div>


As a result, the HTML view will show an unordered list of products.
See the output below.

Attribute Directives
Attribute directives modify the appearance of or define a custom behavior for a DOM element.
Angular has a rich set of built-in directives that allow dynamic styling and classes to be applied.
Among these directives, ngClass and ngStyle are essential tools for any Angular developer.

Let’s try to explore them one by one.

The ngClass
We can use this directive ngClass to add or remove CSS classes dynamically.
Moreover, developers can use this directive to apply one or more CSS classes to an element conditionally.
You can pass a string, array, or object to ngClass to control which classes should be added or removed.
You can use either the expression or method with the ngClass directive.

Using Expression
A developer can’t write if condition within the ngClass directive.

However, we can use the ternary operator as this is an expression.
//Syntax
[ngClass]="condition ? 'when true apply class' : 'when false apply class'"
//Syntax (multiple classes)
[ngClass]="condition ? 'when true apply class1 class2' : 'when false apply class1 class2'"


Let’s have an example below.
attribute-directive-samp.component.css

.dot {
  height: 100px;
  width: 100px;
  border-radius: 50%;
  display: inline-block;
  background-color: #c1bbbb;
}
.dot-border-red {
  border-color: red;
  border-style: dotted;
  border-width: 3px;
}

.dot-border-yellow {
  border-color: yellow;
  border-style: dotted;
  border-width: 3px;
}
.yellow {
  background-color: yellow;
}

.red {
  background


attribute-directive-samp.component.ts
import { Component } from '@angular/core';
import {NgClass} from '@angular/common';

@Component({
  selector: 'app-attribute-directive-samp',
  standalone: true,
  imports: [
    NgClass
  ],
  templateUrl: './attribute-directive-samp.component.html',
  styleUrl: './attribute-directive-samp.component.css'
})
export class AttributeDirectiveSampComponent {
  isYellow = false;
  isRed: boolean = false;

  colorChanged(value:string): void {
    if(value === 'R'){
      this.isRed = true;
      this.isYellow = false;
    }
    else if(value === 'Y'){
      this.isYellow = true;
      this.isRed = false;
    }
  }
}

attribute-directive-samp.component.html
<h3>Using Expression</h3>
<input type="radio" name="firstDot" value="R" (change)="colorChanged('R')" /> Red
<input type="radio" name="firstDot" value="Y" (change)="colorChanged('Y')" /> Yellow
<br/>
<div class="dot" [ngClass]="isRed ? 'dot red dot-border-yellow': 'dot yellow dot-border-red'">
</div>

From our example, we have seen that we can change the circle’s background color and border when choosing between red and yellow.
We have achieved this by using an expression inside the ngClass.

Output


Using Function
Developers can apply CSS classes through various methods in complex conditions.

For example, you can use this way to set a CSS class based on user input.

Let’s see an example below.
attribute-directive-samp-using-function.component.css

.dot {
  height: 100px;
  width: 100px;
  border-radius: 50%;
  display: inline-block;
  background-color: #c1bbbb;
}
.dot-border-red {
  border-color: red;
  border-style: dotted;
  border-width: 3px;
}

.dot-border-yellow {
  border-color: yellow;
  border-style: dotted;
  border-width: 3px;
}
.yellow {
  background-color: yellow;
}

.red {
  background-color: red;
}

attribute-directive-samp-using-function.component.ts
import { Component } from '@angular/core';
import {FormsModule} from '@angular/forms';
import {NgClass} from '@angular/common';

@Component({
  selector: 'app-attribute-directive-samp-using-function',
  standalone: true,
  imports: [
    FormsModule,
    NgClass
  ],
  templateUrl: './attribute-directive-samp-using-function.component.html',
  styleUrl: './attribute-directive-samp-using-function.component.css'
})
export class AttributeDirectiveSampUsingFunctionComponent {
  selectedColor: string = "";

  getClassColorValue(): string {
    let classToReturn = '';
    if(this.selectedColor === 'Red'){
      classToReturn = 'dot red dot-border-yellow';
    }
    else if(this.selectedColor === 'Yellow'){
      classToReturn = 'dot yellow dot-border-red';
    }
    return classToReturn;
  }
}


attribute-directive-samp-using-function.component.html
<h3>Using Function</h3>
<input type="radio" name="secondDot" value="Red" [(ngModel)]="selectedColor" /> Red
<input type="radio" name="secondDot" value="Yellow" [(ngModel)]="selectedColor" /> Yellow
<br/>
<div class="dot" [ngClass]="getClassColorValue()"></div>


From our example, we have seen that we can change the circle’s background color and border when choosing between red and yellow.
However, instead of an expression, we used a method or function where the class was set inside the ngClass.
Note. For both examples, we use the same styles for attribute-directive-samp.component.css and attribute-directive-samp-using-function.component.css.
Again, we have achieved our goal for both examples, but by using different approaches, it's up to the developer to choose either expression or method/function.

Output

 

The ngStyle
Developers, when using the ngStyle directive, allow them to set the style property of the DOM element.

People suggest directly putting styles inside the style attribute isn’t that good.
But in our case, and for educational purposes, we need to understand that this directive is available for us to use in some cases.

Let’s see an example.

attribute-directives-ngstyle.component.ts

import {Component} from '@angular/core';
import {NgStyle} from '@angular/common';
import {FormsModule} from '@angular/forms';

@Component({
  selector: 'app-attribute-directives-ngstyle',
  standalone: true,
  imports: [
    NgStyle,
    FormsModule
  ],
  templateUrl: './attribute-directives-ngstyle.component.html',
  styleUrl: './attribute-directives-ngstyle.component.css'
})
export class AttributeDirectivesNgstyleComponent {

  isBold : boolean = false;
  isItalic:boolean = false;
  isUpperCase: boolean = false;


  setElementStyle() {
    return {
      'font-weight': this.isBold ? 'bold' : 'normal',
      'font-style': this.isItalic ? 'italic' : 'normal',
      'text-transform': this.isUpperCase ? 'uppercase' : 'none'
    };
  }
}

attribute-directives-ngstyle.component.html

<p>
  Let us style the text below.
  <br/>
  Bold: <input type="checkbox" [(ngModel)]="isBold"  /> <br/>
  Italic: <input type="checkbox" [(ngModel)]="isItalic" /> <br/>
  UpperCase: <input type="checkbox" [(ngModel)]="isUpperCase" /> <br/>
</p>
<div [ngStyle]="setElementStyle()">I love Angular</div>


From our example, we have built an object that checks whether the checkboxes are checked, which makes the isItalic, isUpperCase, and isBold true or false with specific values at runtime.

Then, it will be returned as an object assigned to the ngStyle directive.

See the output below.


Summary
In this post, we have discussed the three types of directives: component, structural, and attribute. However, component directives seem straightforward to most of us developers. We have seen a lot of examples of structural and attribute directives, and the examples we have are the built-in directives for these types of directives built into the Angular library for most use cases. I hope you have enjoyed this article as much as I have enjoyed writing it.
Stay tuned for more information, and don't forget to download the attached project source code.
If you run the project source code, don’t forget to command “npm install.”
Until next time, happy programming, and good luck with your career!



European Visual Studio 2022 Hosting - HostForLIFE :: How to Fix the 'Process with an Id of #### is not Running' Error in Visual Studio?

clock October 15, 2024 08:00 by author Peter

Approach 1

  • Close Visual Studio: Ensure that Visual Studio is completely closed before proceeding.
  • Delete the Hidden .vs Folder
    • Navigate to the folder where your solution files are stored.
    • Find the hidden .vs folder and delete it. You may need to enable viewing hidden files in File Explorer to see this folder.
  • Delete the bin and obj Folders
    • Search within your project directory for the bin and obj folders.
    • Delete these folders to ensure that old build artifacts are cleared.
  • Restart Visual Studio: After deleting the folders, reopen Visual Studio.
  • Rebuild and Debug
    • Press F5 or click the "Start Debugging" button to rebuild the project.
    • IIS Express should load normally, allowing you to debug your application.

Approach 2
Open Visual Studio as Administrator: To avoid permission issues, right-click on the Visual Studio icon and select Run as administrator.

Unload the Project

  • In Solution Explorer, right-click on your project.
  • Click on Unload Project to temporarily unload it.

Edit the .csproj File
Right-click on the unloaded project again and select Edit PROJECT_NAME.csproj (replace PROJECT_NAME with the actual name of your project).
Remove the IIS Express Configuration

In the .csproj file, locate the following lines of code.
<DevelopmentServerPort>45678</DevelopmentServerPort>
<DevelopmentServerVPath>/</DevelopmentServerVPath>
<IISUrl>http://localhost:45678/</IISUrl>

Delete these lines to remove the custom port settings.

Save and Close the .csproj File: After making the changes, save the file and close it.

Reload the Project
Right-click the unloaded project again and select Reload Project. By following these steps, you can reset your project's IIS Express configuration and resolve port-related issues.



AngularJS Hosting Europe - HostForLIFE.eu :: Integration of Angular with Microservices

clock October 10, 2024 07:00 by author Peter

I'm a slack backend.net developer. I have some knowledge of.net technologies, however I'm not very knowledgeable with Angular, a frontend JavaScript framework. In order to enable external communication between the front-end and RESTful web API services, my manager instructed me to jot down certain typescript codes. You all know what would happen if I told him I didn't know how to do it. Anyhow, let's return to the primary topic. Please be aware that this is only intended for novice users who want to fire once and forget. Please don't hold me responsible. My knowledge of typescripts is rather limited.

Resolution and Schematic Design

  • I divided the entire assignment into four sections at first:
  • Examining the options in the app.
  • Setting up an environment depends on whether it's for production, QA, or development.
  • Establishing a connection with external RESTful web API services.
  • Requests to the services that include instructions or questions.

Basic knowledge - I guess you know it. So, in short.

  • Restful web API: it’s an interface for communication with two or more applications.
  • TypeScript: Compared to javaScript, It supports writing code with object-oriented concepts.
  • Singleton design pattern: It creates a single shared instance of the object.
  • Dependency injection design pattern: It is a style of object configuration in which objects are set by an external entity.

Explanation of each of the steps

  • Step 1: Read all the configuration at runtime from the appSettings.json file so that applications can use this data at runtime.
  • Step 2: Check the environment. Is it development, QA, or production? Set the environment settings data that you got from step 1.
  • Step 3: Create a base class for the service to get the API service, for instance. Design it using the concept of the singleton design pattern. Get the settings data from step 2.
  • Step 4: The main service class calls all the get/post/put/patch/delete required requests to the RESTful web API. Add the base class from step 3.
  • Step 5: Use the dependency Injection pattern to inject the dependent service. Inject the dependent service class into the component class. Call the required methods of the service from the component class. Use the class from step 4.

Implementation of each of the classes using typeScript in the Angular project

  • appsettings-json-reader package: Read all the data from the JSON file.
  • npm install appsettings-json-reader

Axios package: Promise-based API method called.
npm install axios --save

I guess you already know how to implement step1 & step2.

Implementing steps 3
Creating the base class using a command.
ng g class BaseApiClientService

import { Injectable } from "@angular/core";
import axios from "axios";
import { AppSettingsConfig } from "../../configuration/app-settings-config";

@Injectable()
export class BaseApiClientService {
  private appSettings!: AppSettingsConfig;
  private helloApiBaseUrl!: string;

  constructor() {
    // Holding configuration-data object.
    this.appSettings = new AppSettingsConfig();

    // Getting base URL of the Hello-API.
    this.helloApiBaseUrl = this.appSettings.apiEndPoint;
  }

  // Main API Instance.
  readonly HelloApiInstance = () => {
    return axios.create({
      baseURL: this.helloApiBaseUrl,
      timeout: 5000,
      headers: {
        Accept: 'application/json',
        cors: true,
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, PATCH, OPTIONS',
      }
    });
  }
}


Implementing steps 4
Creating the service class using a command.
ng g service Hello-Api-Service

import { Injectable } from '@angular/core';
import { AxiosInstance } from 'axios';
import { ConstApiSubPathConfig } from '../../configuration/const-api-sub-path-config';
import { BaseApiClientService } from './base-api-client-service';

@Injectable({
  providedIn: 'root'
})
export class HelloAPIServiceService {
  readonly helloWebApiInstance: AxiosInstance;

  constructor(private baseClient: BaseApiClientService)
  {
    this.helloWebApiInstance = this.baseClient.HelloApiInstance();
  }

  GetHelloDataList(isActive:boolean) {
    //// It will add the pathSufix with the main base URL path.
    let pathSufix = '/' + ConstApiSubPathConfig.HelloApiSubDaListPathSufix;

    //// Get request:Returns the response.
    return this.helloWebApiInstance.get(pathSufix, {
      params: { IsActive: isActive }});
  }

  AddHelloMessage(helloMessageObj: any) {
    let pathSufix = '/' + ConstApiSubPathConfig.HelloApiSubPathSufix;

    //// Post request:Returns the response.
    return this.helloWebApiInstance.post(pathSufix, helloMessageObj);
  }
}

Implementing Steps 5
Creating the component class using a command.
ng g component HelloServiceGrid --module app

import { Component } from '@angular/core';
import { HelloAPIServiceService } from '../../../core/service/axios-service/hello-api-service.service';

@Component({
  selector: 'app-hello-service-grid',
  templateUrl: './hello-service-grid.component.html',
  styleUrls: ['./hello-service-grid.component.css']
})
export class HelloServiceGridComponent {
  constructor( private api: HelloAPIServiceService){  }
  getHelloDataList()
  {
      let isActive:boolean = true;
      this.api.GetHelloDataList(isActive)
      .then(response => {

        //// if status-code is success.
        if (response.status === 200) {
          /// Response Data from API.
          let result = response.data;

          //// Implement your logic with the data below:
        }
      }).catch(error => console.log('Error message =====> Sorry : ' + error.message));
  }
}


Don’t forget to check the App.module.ts file. Your components should be added to the declarations array, and your services should be added to the providers array.


I'll go over how to define environmental configurations and read configurations at runtime in the next section, which covers leveraging Azure DevOps CI/CD pipelines to deploy an Angular app to the Azure environment. Anyhow, I have to leave.



AngularJS Hosting Europe - HostForLIFE.eu :: How to Apply CRUD Operations in Dynamic Grid Using AngularJS?

clock October 3, 2024 08:08 by author Peter

I explained How to Show Data in a Dynamic Grid Using AngularJS in my earlier article. I'll explain in this article how to use AngularJS to apply CRUD operations in a dynamic grid. I previously shown to you how to display data in a grid format, but in this post, we'll take it a step further and enable editing of the grid; in other words, I'll be providing CRUD functions for the grid.

Step 1: Since I'm working on an earlier application, you may see where I left off in that post by reading it.
Now, I will update the JavaScript section and will provide the edit and delete functionality. For that, you need to write this code in the script section.
$scope.delete = function(id) {
    for (i in $scope.employees) {
        if ($scope.employees[i].id == id) {
            $scope.employees.splice(i, 1);
            $scope.newEmployee = {};
        }
    }
}

$scope.edit = function(id) {
    for (i in $scope.employees) {
        if ($scope.employees[i].id == id) {
            $scope.newEmployee = angular.copy($scope.employees[i]);
        }
    }
}


First, I provided the delete functionality; for this, I have created a function named "delete". In this function the ID of the Employee is passed, if the ID correctly matches one of the existing IDs then the delete operation will be done and that entry will be deleted.

Similarly, I have created the "Edit" function. In this function, the ID of the Employee will also be passed, but this time the data related to that ID will not be deleted. Instead, it will be passed back to the corresponding textboxes so that the user can make changes, and when the user clicks the save button, the data will again be saved at the same Id position as it was stored previously.

Now, the updated Script looks like this.
<script>
    var empid = 1;

    function x($scope) {
        $scope.employees = [
            { id: 0, 'name': 'Anubhav', 'address': 'Ghaziabad', 'dept': 'Developer' }
        ];

        $scope.saveRecord = function() {
            if ($scope.newEmployee.id == null) {
                $scope.newEmployee.id = empid++;
                $scope.employees.push($scope.newEmployee);
            } else {
                for (i in $scope.employees) {
                    if ($scope.employees[i].id == $scope.newEmployee.id) {
                        $scope.employees[i] = $scope.newEmployee;
                    }
                }
            }
            $scope.newEmployee = {};
        }

        $scope.delete = function(id) {
            for (i in $scope.employees) {
                if ($scope.employees[i].id == id) {
                    $scope.employees.splice(i, 1);
                    $scope.newEmployee = {};
                }
            }
        }

        $scope.edit = function(id) {
            for (i in $scope.employees) {
                if ($scope.employees[i].id == id) {
                    $scope.newEmployee = angular.copy($scope.employees[i]);
                }
            }
        }
    }
</script>

Step 2. Now, I will work on the ViewModel of this application and will modify it as well.
You need to update your Table with this code.
<table border="1" bordercolor="blue">
    <tr style="color:blue">
        <th style="width:150px">Name</th>
        <th style="width:150px">Address</th>
        <th style="width:150px">Dept</th>
        <th>Action</th>
    </tr>
    <tr style="color:pink" ng-repeat="employee in employees">
        <td>{{ employee.name }}</td>
        <td>{{ employee.address }}</td>
        <td>{{ employee.dept }}</td>
        <td>
            <a href="#" ng-click="edit(employee.id)">edit</a> |
            <a href="#" ng-click="delete(employee.id)">delete</a>
        </td>
    </tr>
</table>


Here, in the first Row, I added one more heading, "Action". In the second row, I added one more column in which two Anchors are used.

The first Anchor click is bound to the "Edit" function, and the second Anchor click is bound to the "Delete" function.

The ID of the Employee is passed depending on the Anchors, in other words wherever the Anchors are placed, the corresponding ID will be passed to the function.

Now our View Model is updated and its code is like this.
<div ng-app="" ng-controller="x">
    <label>Name</label>
    <input type="text" name="name" ng-model="newEmployee.name"/>

    <label>Address</label>
    <input type="text" name="address" ng-model="newEmployee.address"/>

    <label>Dept.</label>
    <input type="text" name="dept" ng-model="newEmployee.dept"/>
    <br/>

    <input type="hidden" ng-model="newEmployee.id"/>
    <input type="button" value="Save" ng-click="saveRecord()" class="btn btn-primary"/>
    <br/>
    <br/>

    <table border="1" bordercolor="blue">
        <tr style="color:blue">
            <th style="width:150px">Name</th>
            <th style="width:150px">Address</th>
            <th style="width:150px">Dept</th>
            <th>Action</th>
        </tr>
        <tr style="color:pink" ng-repeat="employee in employees">
            <td>{{ employee.name }}</td>
            <td>{{ employee.address }}</td>
            <td>{{ employee.dept }}</td>
            <td>
                <a href="#" ng-click="edit(employee.id)">edit</a> |
                <a href="#" ng-click="delete(employee.id)">delete</a>
            </td>
        </tr>
    </table>
</div>


Now, our application is created and is ready for execution.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in