2

Trying to figure out an 'Angular specific' way to try and achieve this. I have a page with some views. When a user clicks an anchor, the views change, which I have working just fine.

What I'm curious is, if when the user clicks, is it possible to store a variable (say the inner html) then pass it to the $routeProvider to load the view a bit more dynamically?

So for anchor tag #name1, when that view is displayed, I can pass name1 into nameHolder as a variable to load some files with the same name.

HTML

<script type="text/ng-template" id="this.html">    
  This Page.
</script>
<script type="text/ng-template" id="that.html">
  That Page.
</script>

<div>
  <ul>
    <li><a href="#/this">this</a></li>
    <li><a href="#/that">that</a></li>
  </ul>
  <ng-view></ng-view>
</div>

JS

var nameHolder= [];

var app = angular.module( "myApp", ['ngRoute'] );

app.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/' + nameHolder, {
        templateUrl: nameHolder + ".html",
        controller: 'individ',
        nameofuser: nameHolder
    }).
      when('/', {
        templateUrl: 'this.html'
    });
}]);

app.controller('individ', function($scope, $route) {
  $scope.img =  $route.current.nameofuser;
});

$(document).ready(function(){
  $('a').click(function(){
    nameHolder.length = 0;
    var pushThis = $(this).text();
    nameHolder.push(pushThis);
    console.log(nameHolder)
  });
});

Thanks for any info.

Here's a JSFiddle

1 Answer 1

5

You can use function for templateUrl to dynamically construct url. This function accepts an object of route parameters:

$routeProvider.
    when('/:nameHolder', {
        templateUrl: function(params) {
            return params.nameHolder + ".html";
        },
        controller: 'individ',
        nameofuser: nameHolder
}).
Sign up to request clarification or add additional context in comments.

2 Comments

awesome solution, thank you. Updated working fiddle with your code. I didn't realize I could pass a function with 'templateUrl'. jsfiddle.net/GregWebBandit/rdko8qqs/9
Updated reusing the "this.html" tpl. jsfiddle.net/GregWebBandit/rdko8qqs/11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.