Wannabe Coder
Wannabe Coder

Reputation: 697

Using Dynamic templateUrl for links built at runtime

I am writing an AngularJS website and I need a dynamic templateUrl.

If I hardcode my url template, my routing works.

when('/levelthree', {
    templateUrl: 'views/levelthree/1.001_WhitePaper.htm',
    controller: 'LevelThreeController'
}).

When I try this, it does not.

when('/levelthree', {
    templateUrl: function () {
        return 'views/levelthree/' + retrieveStorageItem('LevelThreeDocumentSelected');
    },
    controller: 'LevelThreeController'
}).

How can I have a dynamic templateUrl that works while passing in the document url when clicked on?

// HREF
<a id=\"a0\" style=\"color: rgb(0, 0, 0);\" href=\"#levelthree\" data-url=\"1.001_WhitePaper.htm\">White Paper <i 
    class=\"fa fa-play\" style=\"color: rgb(0, 128, 0);\"></i></a>

// URL of the HREF, when clicked.
http://localhost:65155/testwebsite/Index.html#levelthree

// Code that gets the document I need.
$(document).on("click", ".openLevelThree", function (e) {
    var documentSelected = $(this).children('a').attr('data-url');

    setStorageItem("LevelThreeDocumentSelected", documentSelected);
});

I've looked at this but I do not see where I would have access to the $scope to see if it would work for me.

Upvotes: 3

Views: 51

Answers (1)

Rogerio Soares
Rogerio Soares

Reputation: 1613

The link you provide is for directives, below a sample to do handle that. Try to avoid as you can jquery when working with angular.

var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider) {
  localStorage.setItem("LevelThreeDocumentSelected", "1.001_WhitePaper.htm");

  $routeProvider
    .when('/', {
      template: '<h3>Home view</h3>' +
      '<button ng-click="setLevelThreeDocuments(\'1.001_WhitePaper.htm\')">1</button>' +
      '<button ng-click="setLevelThreeDocuments(\'2.002_WhitePaper.htm\')">2</button>' +
      '<button ng-click="setLevelThreeDocuments(\'3.003_WhitePaper.htm\')">3</button>',
      controller: 'mainController'
    })
  .when('/levelthree', {
    templateUrl: function() {
      var url = localStorage.getItem('LevelThreeDocumentSelected');
      console.log(url);
      return url;
    },
    controller: 'LevelThreeController'
  })
});

app.controller('mainController', function($scope) {
  $scope.setLevelThreeDocuments = function(s) {
    localStorage.setItem("LevelThreeDocumentSelected", s);
  }
});

app.controller('LevelThreeController', function($scope) {
  $scope.message = 'I am LevelThreeController';
});

https://plnkr.co/edit/VZ7WLlIEKq1gpy156GjJ?p=preview

Upvotes: 1

Related Questions