Overview
In this article, we will see how to use $anchorScroll with database. In our database, there are two tables, countries and cities. We will disable countries and their respective cities on a webpage with the help of AngularJS. In previous articles, we have seen how to use anchorScroll part .

For more articles on AngularJS, refer here.
- Overview Of AngularJS
- Modules And Controller In AngularJS
- Controllers in AngularJS
- AngularJS ng src Directive
- AngularJS ng-Repeat Directive
- Handling Events In AngularJS
- How To Use Two-Way Data Binding In AngularJS
- Filters In AngularJS
- Sorting Data In AngularJS
- Sorting Rows By Table Header In AngularJS
- Creating Custom Filters In AngularJS
- ng-Hide And ng-Show In AngularJS
- ng-init Directive In AngularJS
- Search And MultiSearch In AngularJS
- ngInclude Directive In AngularJS
- $http Service In AngularJS
- Consuming ASP.NET WebService In AngularJS
- AnchorScroll Service In AngularJS
First, we create tables and insert some data into those. So, let's create a table called Country.
- Create Table Country
- ( Id int primary key identity,
- name varchar(50)
- )
- insert into country values('India')
- insert into country values('USA')
- insert into country values('UK')
- Create table City
- (id int primary key identity,
- name varchar(50),
- CountryId int foreign key references country(Id))
- insert into City values('Mumbai', 1)
- insert into City values('Chennai', 1)
- insert into City values('Bangalore', 1)
- insert into City values('Delhi', 1)
- insert into City values('New York', 2)
- insert into City values('LA', 2)
- insert into City values('Chicago', 2)
- insert into City values('London', 3)

Now, let's add connectionString in our web.config file.
- <connectionStrings>
- <add name="Test" connectionString="Data Source=IBALL-PC;Initial Catalog=TEST;Persist Security Info=True;User ID=sa;Password=p@ssw0rd" providerName="System.Data.SqlClient" /> </connectionStrings>
- <system.web>
- <compilation debug="true" targetFramework="4.0" />
- <webServices>
- <protocols>
- <add name="HttpGet" /> </protocols>
- </webServices>
- </system.web>
- public int Id { get; set; }
- public string Name { get; set; }
- public string CountryId { get; set; }
- public class Country {
- public int Id {
- get;
- set;
- }
- public string Name {
- get;
- set;
- }
- public List < City > Cities {
- get;
- set;
- }
- }
Now, let's create a webService. Right click on the Web and create a webService.

Name this service as CountryService.asmx.
In that, add these imports as we are using some of the ADO.NET code for our web service.
- using System.Data;
- using System.Data.SqlClient;
- using System.Configuration;
- using System.Web.Script.Serialization;
- public void GetData() {
- List < Country > listCountries = new List < Country > ();
- string cs = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
- using(SqlConnection con = new SqlConnection(cs)) {
- SqlCommand cmd = new SqlCommand("select * from Country;Select * from City ", con);
- SqlDataAdapter da = new SqlDataAdapter(cmd);
- DataSet ds = new DataSet();
- da.Fill(ds);
- DataView dataview = new DataView(ds.Tables[1]);
- foreach(DataRow countryDataRow in ds.Tables[0].Rows) {
- Country country = new Country();
- country.Id = Convert.ToInt32(countryDataRow["Id"]);
- country.Name = countryDataRow["Name"].ToString();
- dataview.RowFilter = "CountryID='" + country.Id + "'";
- List < City > listcities = new List < City > ();
- foreach(DataRowView cityDataRowView in dataview) {
- DataRow cityDataRow = cityDataRowView.Row;
- City city = new City();
- city.Id = Convert.ToInt32(cityDataRow["Id"]);
- city.Name = cityDataRow["Name"].ToString();
- city.CountryId = cityDataRow["CountryId"].ToString();
- listcities.Add(city);
- }
- country.Cities = listcities;
- listCountries.Add(country);
- }
- }
- JavaScriptSerializer js = new JavaScriptSerializer();
- Context.Response.Write(js.Serialize(listCountries));
- }

The highlighted section in the above picture contains an ADO.NET code that shows, we are displaying the list of countries as India, USA, and UK respectively. Similarly, we are using a Connection String called Test which we passed in our web.config file.
Now, we are just trying to establish our connection with our SQL Server by using sqlconnection statement and passing those two queries.
Now, loop those records as,

Here, we are using foreach statement to loop those records. In the first foreach, we are looping those as list of countries, in which we are passing those corresponding names and cities too.
In the next foreach statement, we are looping the list of cities. If India is the country, then the list of cities displays the cities as Bangalore,Chennai, and so on.
Now, let's test our service. Run the service.

Click on GetData.

Now, invoke the service and see the output.

As you can see, we got the desired JSON output.
Now, we will add some code to our Controller. Let's include a JavaScript file and name it as Script.js.

In this file, just add AngularJS reference.
- /// <reference path="angular.js" />
Drag and drop the AngularJS file.
Now, we add a Module named as demoApp and assign a Controller named as CountryController. In that, we will add a function where we add the following:
- $scope
- $http
- $location and
- $anchorScroll
- var demoApp = angular.module("demoApp", [])
- .controller("countryController", function ($scope, $http, $location, $anchorScroll)
- $http.get("CountryService.asmx/GetData")
- .then(function (response) {
- $scope.countries = response.data;
- });
Now, just add this code.
- $scope.scrollTo = function(countryName) {
- $location.hash(countryName);
- $anchorScroll();
- }
So, our final code is.
- /// <reference path="angular.js" />
- var demoApp = angular.module("demoApp", []).controller("countryController", function($scope, $http, $location, $anchorScroll) {
- $http.get("CountryService.asmx/GetData").then(function(response) {
- $scope.countries = response.data;
- });
- $scope.scrollTo = function(countryName) {
- $location.hash(countryName);
- $anchorScroll();
- }
- });

First, we add the reference of our script file and Angular file too.
- <script src="scripts/angular.js"></script>
- <script src="scripts/Script.js"></script>
- <link href="Style.css" rel="stylesheet" />
- <html ng-app="demoApp">
- <body ng-controller="countryController">
- <span ng-repeat="country in countries">
- <button ng-click="scrollTo(country.Name)">{{country.Name}}</button>
- </span>
- <br/><br/>
- <div>
- <fieldset ng-repeat="country in countries" id="{{country.Name}}">
- <legend>{{country.Name}}</legend>
- <ul>
- <li ng-repeat="city in country.Cities">
- {{city.Name }}
- </li>
- </ul>
- </fieldset>
- </div>
As we are looping those records, we are using ng-repeat directive and displaying its country name and cities name respectively .
So, our final HTML page code is.
- <!DOCTYPE html>
- <html ng-app="demoApp">
- <head>
- <title></title>
- <meta charset="utf-8" />
- <script src="scripts/angular.js"></script>
- <script src="scripts/Script.js"></script>
- <link href="Style.css" rel="stylesheet" />
- </head>
- <body ng-controller="countryController">
- <span ng-repeat="country in countries">
- <button ng-click="scrollTo(country.Name)">{{country.Name}}</button>
- </span>
- <br/><br/>
- <div>
- <fieldset ng-repeat="country in countries" id="{{country.Name}}">
- <legend>{{country.Name}}</legend>
- <ul>
- <li ng-repeat="city in country.Cities">
- {{city.Name }}
- </li>
- </ul>
- </fieldset>
- </div>
- </body>
- </html>
- body {
- font-family:Arial;
- }
- div {
- display:block;
- font-size:xx-large;
- height:350px;
- width:400px;
- border:1px solid black;
- padding:10px;
- overflow-y:scroll;
- }

We have got the desired output.
When click on India, see the URL. A # has appeared.

Similarly, for USA and UK also, we are able to scroll through.
Conclusion
This was all about $anchorScroll service with database. Hope this article was helpful.

Debasis SahaPosted Sep 7, 2016, 9:18 AM
Nice one
Prasanna MuraliPosted Sep 6, 2016, 9:17 PM
Nice post...