UI router get state name from object / function

I wonder if there is a way to refer to states in terms of an object or function?

Just to separate views from state definitions. For instance. if I change the name of the state, I don’t need to change it everywhere in my views.

+4
source share
1 answer

One of the solutions described below can be found here as a working plunker

In this example, we will determine the state for some object (for example, an employee), for example:

  • list and
  • in detail .

Let us use some variable entityNameto play the role of a decoupled naming convention:

var entityName = "employee";

$stateProvider
    .state(entityName, {
        url: '/' + entityName,
        views: {
          ...
      }})

    .state(entityName + '.detail', {
        url: '/{{Id}}',
        views: {
          ...
      }});

( , ):

<a ui-sref="{{detailLink(item)}}" >{{item.Name}}</a>

detailLink(item). controller , ListModel, (, ), detailLink.

controller:['$scope','$state',
  function ( $scope , $state){ 

      $scope.detailLink = function (item){

          // here we get the employee in run-time
          var currentState = $state.current.name; 
          var sref = currentState + '.detail({Id:' + item.Id + '})';
          return sref;
      };
}],

. ... ( defintion)

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

    var entityName = "employee";

    $stateProvider
      .state(entityName, {
        url: '/' + entityName,
        views: {
          body: {
          template: '<div>' +
                    '  <h2>List View</h2> ' +
                    '  <ul ng-repeat="item in items"> ' +
                    '   <li><a ui-sref="{{detailLink(item)}}" >{{item.Name}}</a>' +
                    '  </li></ul>' +
                    '  <h2>Detail View</h2> ' +
                    '  <div ui-view="detail"></div>' +
                    '</div>',
          controller:['$scope','$state',
            function ( $scope , $state){ 

              $scope.items = [{Name : "Abc", Id : 0}, {Name : "Def", Id : 1}];

              $scope.detailLink = function (item){

                 var currentState = $state.current.name;
                 return currentState + '.detail({Id:' + item.Id + '})';
              };
          }],
        }
      }})
      .state(entityName + '.detail', {
        url: '/{{Id}}',
        views: {
          detail: {
          template: '<div>' +
                    '  <label>{{item.Name}} ' +
                    '  <input ng-model="item.Name"}}" type="text" />' +
                    '  <div>current state name: <i>{{state.name}}<i></div> ' +
                    '</div>',
          controller:['$scope','$stateParams','$state',
            function ( $scope , $stateParams , $state){ 
              $scope.state = $state.current
              $scope.item = $scope.items[$stateParams.Id];
          }],
        }
      }});

}])
+8

Source: https://habr.com/ru/post/1540090/


All Articles