1

So lets say I am writing a custom directive that loads a template into a div. My custom directive is called loadClickedTpl. When loadClickedTpl is clicked it should read the attribute and load the template into #target.

So far my html looks something like this:

 <html np-app="mymodule">
 <head>...</head>
 <body>
 <a loadClickedTpl tplSrc="myTpl" > Click Me to load template </a>
 <div id="target" ng-include src="clickedTpl"></div>
 <script type="text/ng-template" id="myTpl">
 <h1>Loaded</h1>
 </script>
 </body>
 </html>

The problem is setting the clickedTpl var to point to the template. If its done in the html like so <div id="target" ng-include src="'myTpl'"></div> it works fine, doing it programmatically is proving to be a challenge. Here is what I have tried so far:

angular.module('loadATpl').directive 'loadClickedTpl', ->
 (scope, element, attrs) ->
 element.bind 'click', -> 
 # does not work
 scope.clickedTpl = attrs.tplSrc
 # also does not work
 angular.injector(['ng']).invoke ($rootScope) ->
 $rootScope.clickedTpl = attrs.tplSrc
 # obviously does not work
 clickedTpl = atts.tplSrc
angular.module('mymodule', ['loadATpl'])

The click binding does work, but that is were it ends.

asked Apr 16, 2013 at 4:04
1
  • Don't call angular.injector as that will create a new injector. Rather, inject $injector into your directive. See also stackoverflow.com/a/14743553/215945 If you want access to $rootScope, you can just inject it into your directive. Commented Apr 16, 2013 at 15:09

1 Answer 1

10

Here is the working sample: http://plnkr.co/edit/8BNYr9J8g6tRLMo8VdPi?p=preview

You need to use attrs as 'load-clicked-tpl' (hyphenated expression) for angular directives.

answered Apr 16, 2013 at 4:29
Sign up to request clarification or add additional context in comments.

3 Comments

Ok, that sort of works. When its a separate module like in my example it stops though. plnkr.co/edit/IsW1Yf6Ye8HuROO7KMVW
You have to put dependency even if it is empty, try: angular.module('loader', [])
Turns out it was a more complex scope problem angular.element(document).scope() ended up saving me. That and you gave me a big nudge.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.