我想构建一个简单的hello
指令,如下所示:
<hello foo="bar"></hello>
如果foo
属性等于“bar”,我想用<div ng-show="true"></div>"
替换元素;否则,将其替换为<div ng-show="false"></div>"
。但是,我只想替换hello
元素,而不是嵌套在其中的任何子元素!
例如:
<hello foo="bar">
<h1>Hi everyone!</h1>
</hello>
将被替换为:
<div ng-show="true">
<h1>Hi everyone!</h1>
</div>
这甚至可以吗?
答案 0 :(得分:2)
您可以通过使用包含来实现这一目标:
<强>的Javascript 强>
app.directive('hello', function() {
return {
restrict: 'E',
transclude: true,
replace: true,
scope: { foo: '@' },
template: '<div ng-show="foo == \'bar\'" ng-transclude></div>',
};
});
<强> HTML 强>
<hello foo="bar">
<h1>Hi everyone!</h1>
</hello>
<hello foo="baz">
<h1>Hi everybody!</h1>
</hello>
使用Plunker here。
答案 1 :(得分:1)
在编译/链接另一个指令时动态注入指令是一项繁琐的工作。您不能简单地设置属性,因为它不会被Angular收集。手动编译无效,因为它会导致无限循环。话虽如此,如果您已经确定这是您想要的:),请转到:
app.directive('hello', function($injector) {
return {
transclude: true,
replace: true,
restrict: "E",
template: "<div ng-transclude></div>",
compile: function(tele, tattrs) {
var ngShow = $injector.get("ngShowDirective")[0];
return function(scope, ele, attrs) {
attrs.$set("ngShow", (attrs.foo === "bar").toString());
ngShow.link(scope, ele, attrs);
}
}
}
});
这个想法是手动链接ngShow
指令而不是依赖AngularJS来做到这一点。通常,只有AngularJS会调用compile
和link
;此外,此代码依赖于ngShow
具有link
函数的知识。一般来说,它应被视为黑客并谨慎使用。
答案 2 :(得分:0)
您应该只能将ng-show
属性应用于hello
元素,并检查模型的属性以确定它是否应隐藏。
<hello ng-show="foo == 'bar'">
<h1>Hi everyone!</h1>
</hello>
在此视图可访问的范围内,您将拥有foo属性。
$scope.foo = 'bar';