【发布时间】:2016-08-12 17:10:54
【问题描述】:
这就是问题所在。我有一些名为 main-directive 的第三方指令。
app.directive('mainDirective', function() {
return {
scope: {
foo: '&'
// attrs
},
controller: function($scope) {
$scope.click = function() {
window.alert($scope.foo());
}
},
template: '<button ng-click="click()">Click me</button>'
}
});
所以我想创建自己的指令,称为 parent-directive,它将应用程序特定的默认值分配给第三方指令属性。
app.directive('parentDirective', function() {
return {
scope: {
foo: '&?',
attr2: '='
// lots of attrs
},
controller: function($scope) {
$scope.attr1 = "some default value"
$scope.foo = function() {
return "not overrided"
}
if (this.foo) {
$scope.foo = this.foo
}
},
template: '<div class="some-styling"><main-directive foo="foo()" attr1="attr1" attr2="attr2"></main-directive></div>'
}
});
如果我想制作另一个 child-directive 来保持 parent-directive 逻辑。 重载属性很容易我可以使用“编译”功能。但是是否可以覆盖函数呢?
app.directive('childDirective', function() {
return {
scope: false,
require: 'parentDirective',
link: function(scope, element, attr, controller) {
controller.foo = function() {
return "overrided";
}
},
compile: function(element, attr) {
attr.attr2 = "attr2";
}
}
});
使用子作用域而不是孤立作用域可以轻松完成整个事情。 或者通过使用模板扩展。但是,如果我使用模板扩展指令,我将不得不将父“范围”和“模板”定义复制到子指令并转发所有非默认属性,这似乎不是一个优雅的解决方案。
所以关键问题是,有没有一种方法可以在不使用转发属性的情况下使用隔离范围覆盖父指令函数。
这里是DEMO
【问题讨论】:
-
你试过使用$parent吗?如果您的函数在父范围内,您可以使用 $parent 访问它们,然后覆盖它们。
-
确实是的,但是如果在父子指令之间的某个地方会有 ng-if 指令怎么办。在这里使用 $parent 恕我直言不是解决方案。尽管 $parent 被认为是不好的做法。
标签: javascript angularjs