Angularjs - changing templates without changing the url

new for Angular and JS, so my jargon can be turned off.

In a specific section of the page, I would like to load into different templates depending on how the user clicks without changing the URL path. I know how to use $ routeProvider with ng-view, but changing the linked template requires changing the URL.

I would also like to add a backlink in this particular section so that the user can go back.

Any ideas? I could not find any questions like mine, but I can search with the wrong conditions. Any help or suggestions are welcome.

Hi

+4
source share
2 answers

I would suggest using ng-include. This allows you to include fragments of html code from another place. Then you can use ng-show / hide to display the desired fragment or ng-if, if you prefer it to remain outside the dom, if not required

0
source

And for the "Back" button, you will need to save the history array with past clicks / links and click "pop" from this when you click and click. A “complete” solution would look like this:

index.html

<html ng-app="app">
...
<div ng-controller="myController">

  <button ng-click="setCurrentView('tem1')">Template 1</button>
  <button ng-click="setCurrentView('tem2')">Template 2</button>
  <button ng-click="setCurrentView('tem3')">Template 3</button>

  <div ng-include="tem1.html" ng-show="currentView==tem1"></div>
  <div ng-include="tem2.html" ng-show="currentView==tem2"></div>
  <div ng-include="tem3.html" ng-show="currentView==tem3"></div>

  <button ng-click="goBack()">Back</button>

</div>
...
</html>

app.js

angular.module('app',[]).controller('myController',['$scope',function($scope){
  $scope.currentView='tem1';
  var history=[];

  $scope.setCurrentView=function(view){
    history.push($scope.currentView);        
    $scope.currentView=view;
  }

  $scope.goBack=function(){
    $scope.currentView=history.pop();
  }
}]);
+3
source

All Articles