默认情况下,指令不会创建新的作用域。如果您想明确说明,请添加scope: false
根据您的指令:
<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;
}
};
});
fiddle http://jsfiddle.net/mrajcok/gHjU4/
自从有了新楼盘,button
,正在范围上创建,您通常应该使用以下命令创建一个新的子范围scope: true
正如@ardentum-c 在他的回答中所说的那样。新范围将原型继承 https://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs从父范围,这就是为什么你不需要把$parent.back()
到你的 HTML 中。
另一件值得一提的事情是:即使我们正在使用replace: true
,点击元素仍然调用back()
。这是有效的,因为“替换过程将所有属性/类从旧元素迁移到新元素”。 --指导文件 http://docs.angularjs.org/guide/directive
So ng-click='back()' button='go back!'
被迁移到第一个div
在指令的模板中。