3

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

You're wellcome mate :)

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.