0

I'm new to AngularJS Routing. I am trying to find a solution to my problem which is how can I minimize this code at the

 $routeProvider
 .when("/", {
    templateUrl : "main.htm"
 })

So that the input would not be static. To give only one statement instead of the whole 4 statements, the function should recognize automatically the input:

 $routeProvider
.when("/", {
    templateUrl : "main.htm"
})
.when("/red", {
    templateUrl : "red.htm"
})
.when("/green", {
    templateUrl : "green.htm"
})
.when("/blue", {
    templateUrl : "blue.htm"
});

Here is the whole code:

<!DOCTYPE html>
<html>
<script 
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> 
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular- 
route.js"></script>

<body ng-app="myApp">

<p><a href="#/!">Main</a></p>

<a href="#!red">Red</a>
<a href="#!green">Green</a>
<a href="#!blue">Blue</a>

<div ng-view></div>

<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
    templateUrl : "main.htm"
})
.when("/red", {
    templateUrl : "red.htm"
})
.when("/green", {
    templateUrl : "green.htm"
})
.when("/blue", {
    templateUrl : "blue.htm"
});
});
</script>

Click on the links to navigate to "red.htm", "green.htm", "blue.htm", or back to "main.htm"

I am thankful for every solution or suggestion!

Basch
  • 433
  • 4
  • 20
Bratan
  • 107
  • 6
  • 2
    Would this stackoverflow post provide any information on the solution you're after? https://stackoverflow.com/questions/11534710/angularjs-how-to-use-routeparams-in-generating-the-templateurl – slee423 May 12 '18 at 13:11
  • Thank you! But unfortunately i did not understand the solution :( Do you know how to apply the solution here, you would save my day:) – Bratan May 12 '18 at 13:22
  • For this case I don't, sorry. For me I don't see an added benefit of having a dynamic function to handle each of the template URLs because normally with angularjs you'd also apply a controller to each template you wish to load and this would handle your website functionality. Therefore, you'd already be extending on what's to be passed to generate each navigation. I could be wrong in saying that though but if you checkout a $routeParams tutorial, not many of them attempt to apply one $routeParams method for all site navigation and it is in fact split into separate functions like you've done. – slee423 May 12 '18 at 13:30
  • The script for angular routes doesn't load. Remove the space between `angular-` and `route`. Your code will start to work. – 31piy May 12 '18 at 13:51

0 Answers0