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.
1 Answer 1
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.
3 Comments
angular.module('loader', [])angular.element(document).scope() ended up saving me. That and you gave me a big nudge.
angular.injectoras that will create a new injector. Rather, inject$injectorinto your directive. See also stackoverflow.com/a/14743553/215945 If you want access to$rootScope, you can just inject it into your directive.