将变量传递给指令模板而不创建新范围 [英] Passing variable to directive template without creating new scope
问题描述
有没有办法使用属性将变量传递给指令而不创建新的作用域?
HTML
JS
.directive('button', function () {返回 {范围: {按钮: '@'},模板:<div><div another-directive></div>{{button}}</div>",替换:真}})
问题是 ng-click='back()'
现在指的是指令范围.我仍然可以执行 ng-click='$parent.back()'
但这不是我想要的.
默认情况下,指令不会创建新的作用域.如果您想明确说明,请将 scope: false
添加到您的指令中:
angular.module('myApp').directive("button", function () {返回 {scope: false,//这是默认值,因此您可以删除此行模板:<div><div another-directive></div>{{button}}</div>",替换:真的,链接:函数(范围、元素、属性){scope.button = attrs.button;}};});
由于在作用域上创建了一个新属性 button
,您通常应该使用 scope: true
创建一个新的子作用域,正如 @ardentum-c 所具有的他的回答.新范围将原型继承从父作用域,这就是为什么你不需要把 $parent.back()
放入你的 HTML 中.
还有一点值得一提:即使我们使用了replace: true
,点击元素仍然会调用back()
.这是有效的,因为替换过程将所有属性/类从旧元素迁移到新元素."-- directive doc
所以 ng-click='back()' 按钮='go back!'
迁移到指令模板中的第一个 div
.
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
}
})
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;
}
};
});
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.
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屋!
查看全文