【发布时间】:2014-11-07 22:46:56
【问题描述】:
我知道我可以根据选项 DOM 属性 template-url="foo.html" 动态设置 templateUrl,代码如下:
angular.module('foo').directive('parent', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
// code
},
templateUrl: function(elem,attrs) {
return attrs.templateUrl || 'some/path/default.html'
}
}
});
但是,我需要更进一步,将此字符串更深一层传递给子指令。
鉴于此 HTML:
在主项目中的使用
<parent parent-template="bar.html" child-template="foo.html"></parent>
子元素在大多数情况下不会暴露,所以如果设置了child-template,则需要隐式替换所有位于父foo.html中的子<child></child>元素的templateUrl。
require: '^parent' 属性将数据从一个范围传递到另一个范围,但在声明它时,我在 templateUrl 中看不到它。
foo.html
<h1>Title</h1>
<child ng-repeat="item in array"></child>
指令
angular.module('foo').directive('parent', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
// code
},
templateUrl: function(elem,attrs) {
return attrs.parentTemplate || 'some/path/default.html'
},
scope: {
childTemplate: '=childTemplate'
}
}
})
.directive('child', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
// code
},
templateUrl: function(elem,attrs) {
return ??? // parent.attribute.childTemplate? || 'some/path/default.html'
},
require: '^parent',
scope: {
childTemplate: '=childTemplate'
}
}
});
【问题讨论】:
-
我刚刚对您的代码进行了编辑,请确保我更改的内容正确(您将第二个指令命名为
parent,就像第一个指令一样,我认为您希望这样命名为child)。谢谢! -
没错。复制/粘贴错误,谢谢!
-
附加到
child指令范围的childTemplate是否有可能覆盖父级的范围?
标签: javascript angularjs templates angularjs-directive angularjs-scope