简体   繁体   中英

How do I keep a reference when using nested views in AngularJS?

I have 4 pages.
2 pages in English and 2 pages in French.

Here are the 4 options :
EN > Page1 - Content: Computer
EN > Page2 - Content: Keyboard

FR > Page1 - Content: Ordinateur
FR > Page2 - Content: Clavier

How do switch a nested view for its equivalent?

I have put together a plnkr.
https://embed.plnkr.co/SZPp0C8guVeTtcLeWJ3T/

Any help is appreciated! Thanks!


Expected Behaviour. When I click on "Francais", say I am on /en/page1/ , I want it to properly re-route to, in this case, /fr/page1 .

预期行为


Actual Behaviour. When I click on "Francais", say I am on /en/page1/ , it re-routes me to /fr and I don't know how to approach the problem at hand.

实际行为

I forked a new plunker and updated it. The challenge was to watch the scope of the route provider to see what prior values existed. Looking at the current state and name you can conditionally control in the controller which view is persisted. to do this I created a new function:

  //evaluate routes
  let checkRouteValues = (oldVal, newVal)=>{
    $scope.vm.message1 = oldVal;
    $scope.vm.message2 = newVal;

    //first check to see if language has changed
    if(newVal === 'english'&& oldVal ==='francais.page1'){
     $state.go('english.page1');
    }else if(newVal === 'english' && oldVal ==='francais.page2'){
         $state.go('english.page2')
    }else if(newVal ==='francais' && oldVal === 'english.page1' ){
        $state.go('francais.page1');
    }else if (newVal ==='francais' && oldVal === 'english.page2' ){
      $state.go('francais.page2');
    }
  }

Then added a watch to see when the state changed:

 //added a watch to monitor the current state
  $scope.currState =$state;
  $scope.$watch('currState.current.name', function (newValue, oldValue){

     checkRouteValues(oldValue, newValue)
  });

The function checkRouteValues() monitors the new and old values and then sets the state based upon the condition. *caveat: I think this solution works for something small scale like this navigation here however if you had multiple pages I would look to go a different route.

updated plunker

I did add some logging in the html so you could see the values change I did change the name of the app from theApp to app so be careful if you cpoy paste.

I did use arrow functions in the code if you don't like arrow functions you can convert it back to

let checkRouteValues = function(oldVal, newVal){...}

I also used let declaration vs. var to isolate variable scope but you can use var as if you prefer.

And finally with my changes change the route english, page one, is always the default loaded route when your app starts but this should give you enough to get you going.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM