How to Use $state Service with ui-router

in #utopian-io6 years ago

AngularJS_logo.svg.fw1.fw.png

Repository

AngularJs GitHub Address
https://github.com/angular/angular.js

My GitHub Address
https://github.com/pckurdu

This Project GitHub Address
https://github.com/pckurdu/How-to-use-state-service-with-ui-router

What Will I Learn?

  • You will learn what is $state Service in UI Router
  • You will learn how to navigate from one state to another.
  • You will learn how to pass/access parameters while navigating from one state to another
  • You will learn how to use AngularJS $stateparams.
  • You will learn how to use AngularJS service.
  • You will learn find() function in AngularJs.

Requirements

Atom Editor

Difficulty

Intermediate

Tutorial Contents

I will show the $ state service in this tutorial. At the end of this tutorial, you will learn what the $ state service is and how to use it.

When using the $state service ui-router, it provides a parameter handler between the two page controllers during page forwarding operations.

ui-router has the ability to be used with parameters. parameters must be used with an href or ui-sref attribute. With the $ state service, we can use the parameters other than the link. For example, when we click on a button we can move the parameters in the function using $ state service.

I have created an example that makes routing easier for the user to understand, and that performs another routing operation that reaches the news list and accesses the news content when any newsletter in the list is clicked.

Let’s coding and enjoying!

When the page is first opened, there will be one button, and when this button is clicked, it will come up to the news list screen.

I can use ui-sref because i have done routing for this button with ui-router. and set the future location of the news list with ui-iew. ui-sref can be used in place of the href in the tag a, and the state's takes its name.

The index.html page's codes are below.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>state Service</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">

    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.2/angular-ui-router.min.js"></script>
    <script type="text/javascript" src="script.js"></script>

  </head>
  <body>
    <div class="container">
      <div class="jumbotron">
        <a ui-sref=’#'>News</a>
      </div>
      <div>
        <div ui-view></div>
      </div>
    </div>
  </body>
</html>



I have installed bootstrap to edit html elements.
We will perform routing instead of the # in the ui-sref attribute state's name in the future.

The image of the screen is like the one pictured below.
angularjs1.JPG


We can now list the news when the news button is clicked.
I will list the title of the news in news.html page and it get this page on the index.html page with ui-view.

In our script.js file we can write our angular code.

First, let's define our app code
var app=angular.module('myApp',['ui.router']);

In order to use ui-router codes, i need to define ui-router module.

I am creating a field for this application that is defined at the index.html page. my codes will work in this area.

In index.html
<body ng-app='myApp'>

I need to define the state in the config file because I will be routing.

I need to define a controller in the state because I will be able to list the news in this controller.

app.config(['$stateProvider',function($stateProvider){
  $stateProvider
  .state('news',{
    url:'/news',
    templateUrl:'news.html',
    controller:'newsCtrl'
  })
}]);



The news list will be ready for routing when we have defined a news list in the controller and we show this list on the news.html page.

Let’s define newsCtrl in script.js

app.controller('newsCtrl',['$scope',function($scope){

$scope.newsData=[
  {newId:1,newTitle:'newTitle1',newContent:'newContent1'},
  {newId:2,newTitle:'newTitle2',newContent:'newContent2'},
  {newId:3,newTitle:'newTitle3',newContent:'newContent3'},
  {newId:4,newTitle:'newTitle4',newContent:'newContent4'}
];

}]);



Let's show this list in news.html.

<div>
  <ul class="list-group">
    <li class="list-group-item" ng-repeat='data in newsData'>
      <button class="btn btn-secondary">{{data.newTitle}}</button>
    </li>
  </ul>
</div>



News headlines will be listed when we click on the news button.

We must first adjust the ui-sref.

In index.html
<a ui-sref='news'>News</a>

When the news button is clicked, the project looks like this.

angularjs2.JPG


The portion of the tutorial up to this point was the routing process with ui-sref. After that we can start moving the parameters using the $ state service.

Create new.html to show the news content.

We need to access each news id so that this page, can be routed. I will create a function, this function works when any news in the news list is clicked. This function will retrieve the news item and route it to the new.html page using the $ state service.

In news.html

<button class="btn btn-secondary" ng-click="do(data.newId)">{{data.newTitle}}</button>

We can now define the state for the routing operation.

In script.js

app.config(['$stateProvider',function($stateProvider){

…
  .state('new',{
    url:'/new/:nid',
    templateUrl:'new.html',
    controller:'newCtrl'
  });

}]);



I created a page that will receive parameters named nid and I have defined the controller.

Now let’s define controller.

app.controller('newCtrl',['$scope'  ,function($scope){

 
}]);



We can now use $ state service.

When the do function is triggered, we code the $ state.go () function.

The go function takes the state name and parameters to be used in the state. It sends them to the page to be redirected.

Let's do a $state service definition to use service in newsCtrl.

app.controller('newsCtrl',['$scope','$state', ,function($scope,$state){

$scope.newsData=[
  {newId:1,newTitle:'newTitle1',newContent:'newContent1'},
  {newId:2,newTitle:'newTitle2',newContent:'newContent2'},
  {newId:3,newTitle:'newTitle3',newContent:'newContent3'},
  {newId:4,newTitle:'newTitle4',newContent:'newContent4'}
];

transporterService.addList($scope.newsData);

$scope.do=function(newId){

  $state.go('new',{
    nid:newId
  })
}



}]);



Where we got the new id in the function and sent it as a new.html parameter. newCtrl also needs to catch this parameter. Service $ stateParams, which is used to trap parameters.

Let's catch the new id and print the consoles.

In newCtrl

$scope.newId=$stateParams.nid;
console.log($scope.newId);



We have reached id, but how do we get to the content?

News list is also defined in newsCtrl but we want to access from newCtrl. We need to communicate between the two controllers.

We can communicate between two controllers using angular service.

The steps we will take:

  • We will define a service with two functions in it. these functions will perform set and get operations.
  • Defined in controller to be created service
  • Controller communication using get and set functions

To do service definition we use the service function of the app object.

In script.js

app.service('transporterService', function() {
  var List = [];

  this.addList = function(newList) {
      List.push(newList);
  };
  this.getList = function(){
      return List;
  };
});



With the addList() function, the external list is equalized to the list in the service. The list equal with the getList() function is opened out.

Let's take the list of the controller named newsCtrl into the service.

app.controller('newsCtrl',['$scope','$state','transporterService',function($scope,$state,transporterService){
…
transporterService.addList($scope.newsData);
…
}



We can now access my list. Let's use the list with the controller named newCtrl.

app.controller('newCtrl',['$scope','$stateParams','transporterService',function($scope,$stateParams,transporterService){

  $scope.newId=$stateParams.nid;
  console.log($scope.newId);

  $scope.News=transporterService.getList();

  $scope.New = $scope.News[0].find(i => i.newId == $scope.newId);

}]);



With the find function we found object in a list whose id is known.

Finally, let's show content in new.html.

<div>
  {{New.newContent}}
</div>



I showed content below.

angularjs3.JPG

Conslusion

In this tutorial we examined the $state service on the example.

If we print the $ state service console, we get the result shown below.

angularjs4.JPG


I showed $state service current property and go functions.

Current property value
angularjs5.JPG


$state.go function value
angularjs6.JPG


Thank you for your interest.

Curriculum

How to Use $state Service with ui-router

What is ui-router in Angularjs

Proof of Work Done


https://github.com/pckurdu/How-to-use-state-service-with-ui-router

Sort:  

Go here https://steemit.com/@a-a-a to get your post resteemed to over 72,000 followers.

Thank you for your contribution.
While I liked the content of your contribution, I would still like to extend few advices for your upcoming contributions:

  • Try to come up with new and more innovative/useful ways to utilize angular js.
  • There is a lot of information on this subject, try to find something more innovative and contribute to the open source community. Example: link

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Hey @pckurdu
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Contributing on Utopian
Learn how to contribute on our website or by watching this tutorial on Youtube.

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.30
TRX 0.12
JST 0.033
BTC 64400.33
ETH 3140.71
USDT 1.00
SBD 3.93