传递变量指令模板,而无需创建新的作用域 [英] Passing variable to directive template without creating new scope
问题描述
有没有办法通过使用属性指令变量,而无需创建一个新的范围是什么?
Is there a way to pass variables using attributes to a directive without creating a new scope ?
HTML
<div ng-click='back()' button='go back'></div>
JS
.directive('button', function () {
return {
scope: {
button: '@'
},
template: "<div><div another-directive></div>{{button}}</div>",
replace: true
}
})
问题是, NG-点击='回()
现指的指令范围。
我仍然可以做 NG-点击='$ parent.back()
,但它不是我想要的。
The problem is that the ng-click='back()'
now refers to the directive scope.
I still can do ng-click='$parent.back()'
but it's not what I want.
推荐答案
默认情况下,指令不会创建一个新的范围。如果你想显式添加范围:假
来的指令:
By default, directives do not create a new scope. If you want to make that explicit, add scope: false
to your directive:
<div ng-click='back()' button='go back!'></div>
angular.module('myApp').directive("button", function () {
return {
scope: false, // this is the default, so you could remove this line
template: "<div><div another-directive></div>{{button}}</div>",
replace: true,
link: function (scope, element, attrs) {
scope.button = attrs.button;
}
};
});
<大骨节病> 小提琴 骨节病>
由于一个新的属性,按钮
,正在对范围内创建,应使用通常创建一个新的子范围范围:真
作为@ ardentum-C在他的回答。新的范围将<一个href=\"http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs\">prototypially从父范围,这就是为什么你不需要把 $ parent.back()
到您的HTML继承。
Since a new property, button
, is being created on the scope, you should normally create a new child scope using scope: true
as @ardentum-c has in his answer. The new scope will prototypially inherit from the parent scope, which is why you don't need to put $parent.back()
into your HTML.
另外一个珍闻提到:尽管我们使用的是更换:真正的
,点击元素还叫回()
。这工作,因为置换过程中迁移所有的属性/类从旧元素新的。 - 指令文档结果所以 NG-点击='回()按钮='回去吧!
迁移到第一个 DIV
在指令中的模板。
One other tidbit to mention: even though we are using replace: true
, clicking the element still calls back()
. That works because "the replacement process migrates all of the attributes / classes from the old element to the new one." -- directive doc
So ng-click='back()' button='go back!'
are migrated to the first div
in the directive's template.
这篇关于传递变量指令模板,而无需创建新的作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!