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.
Introduction
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')
Now, create another table,City and in that, pass the CountryId as foreign key reference.
- Create table City
- (id int primary key identity,
- name varchar(50),
- CountryId int foreign key references country(Id))
Now, we insert the data.
- 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 see the output.
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>
As we are going to use webService HTTP protocol, so add these in your web.config file.
- <system.web>
- <compilation debug="true" targetFramework="4.0" />
- <webServices>
- <protocols>
- <add name="HttpGet" /> </protocols>
- </webServices>
- </system.web>
Now, we will add two class files, Country and City. Here, I have added a class file called City.cs and have assigned the get and set properties.
- public int Id { get; set; }
- public string Name { get; set; }
- public string CountryId { get; set; }
Now, add another class file as Country.cs.
- public class Country {
- public int Id {
- get;
- set;
- }
- public string Name {
- get;
- set;
- }
- public List < City > Cities {
- get;
- set;
- }
- }
As we are going to display the list of cities that belong to class city. Let's add a webService to our project as we are fetching the data from our database.
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;
As the last import says, we are using JSON to process our web service as script.serialization. Now, just copy this code in your web service.
- 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.
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)
Now, we reference the service which we have created.
- $http.get("CountryService.asmx/GetData")
- .then(function (response) {
- $scope.countries = response.data;
-
- });
We have referenced our service by using $http.get and attached it to our $scope object by response the data .
Now, just add this code.
- $scope.scrollTo = function(countryName) {
- $location.hash(countryName);
- $anchorScroll();
- }
As the location uses hash, so when we will click on the button, a hash gets implemented. Similarly, when India button is clicked, it scrolls to Indian cities as we are using .scrollto and in that function, we are passing country name.
So, our final code is.
-
- 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();
- }
- });
Now, just add a simple HTML Page to your solution.
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" />
In that, we add a Module and Controller name.
- <html ng-app="demoApp">
- <body ng-controller="countryController">
Now, add this code.
- <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>
We have added a button to its respective country, as we are using ng-click directive .
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>
Just add some styles to the page.
- body {
-
- font-family:Arial;
- }
- div {
- display:block;
- font-size:xx-large;
- height:350px;
- width:400px;
- border:1px solid black;
- padding:10px;
- overflow-y:scroll;
- }
Now, run the code.
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.