角度范围混乱 [英] angular scope confusion
问题描述
假设我正在编写一个自定义指令,将模板加载到 div 中.我的自定义指令称为 loadClickedTpl
.当点击 loadClickedTpl
时,它应该读取属性并将模板加载到 #target
中.
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
.
到目前为止,我的 html 看起来像这样:
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>
问题是将 clickedTpl
变量设置为指向模板.如果它像这样在 html 中完成 <div id="target" ng-include src="'myTpl'"></div>
它工作正常,以编程方式进行证明成为挑战.这是我迄今为止尝试过的:
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.
推荐答案
这是工作示例:http://plnkr.co/edit/8BNYr9J8g6tRLMo8VdPi?p=preview
您需要将 attrs 用作 'load-clicked-tpl'(带连字符的表达式)以获得 angular指令.
You need to use attrs as 'load-clicked-tpl' (hyphenated expression) for angular directives.
这篇关于角度范围混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!