how to know whether angular ui-router custom data

2019-08-02 22:54发布

问题:

I want to find out whether the data field of a state in a state is inherited from its parent or not. For example,

    $stateProvider.state('parent', {
      data:{
         customData1:  "Hello",
      }
   })
   .state('parent.child', {
      data:{

      }
   });

Here, the child state(parent.child) has no custom data defined.It inherits CustomData1 from its parent(parent). I want to find out whether the data in parent.child is inherited or not.However I dont want to do something like

if(parent.child.data.customData1==parent.data.customData1)
  {
  }

Is there any other way of finding this out?

回答1:

I am not sure, what exactly is your problem here... and I already tried to explain how it works here:

  • How to disable data inheritance of angular ui router states

I created a plunker showing how it could work for you.

Let's have these states. Firstly some parent / child - where child overrides that all

.state('parent', {
  url: '/parent',
  templateUrl: 'tpl.html',
  controller: 'controllerParent',
  data:{
     customData1:  "Hello",
     customData2:  "World!"
  }
})
.state('parent.child', {
  url: '/child',
  templateUrl: 'tpl.child.html',
  controller: 'controllerChild',
  data:{
     customData1:  "Goodbye",
     customData2:  "Problems"
  }
});

And also some other parent child. The customData1 is unchanged here

// Start 
.state('other', {
  url: "/other",
  templateUrl: 'tpl.html',
  controller: 'controllerParent',
  data:{
     customData1:  "Hello",
     customData2:  "Other World!"
  }
})
.state('other.child', {
  url: "/child",
  templateUrl: 'tpl.child.html',
  controller: 'controllerChild',
  data:{
     customData2:  "UI-Router!"
  }
})

So we can see, that paren.child do not match custom data at all, whil other matches at least the customData1. So, this check will always give us answer, if the parent and child data key is matching:

  $scope.isSame = function(dataKey){
     var childData = $state.current.data;  
     var parentData = $state.$current.parent.data;  
     return childData[dataKey] === parentData[dataKey];
  };

And the plunker uses it like:

 {{isSame('customData2')}}

Check it here