我正在开发一个演示仪表板,在该仪表板内有标题。 我正在使用我的“标题”指令“生成”标题。 (希望到目前为止我做的是正确的)
app.js
myapp.directive('header', function() {
return {
templateUrl: '../../partials/header.html'
};
});
header.html:
<h1>Logo</h1>
<span>{{breadcrumbs}}</span>
partials/dashboard.html
<header breadcrumbs="home"></header>
我可以使用“面包屑”数据并将其传送到我加载的页眉模板吗?
尝试了以下但没有成功:
myapp.directive('header', function() {
return {
breadcrumbs: 'for the sake of this example it can be static',
templateUrl: '../../partials/header.html'
};
});
最佳答案
存在两种实现目标的方法:
您可以使用隔离作用域:
myapp.directive('header', function() {
return {
scope: {
breadcrumbs: "@"
},
templateUrl: '../../partials/header.html'
};
});
或 attr
link
的属性功能:
myapp.directive('header', function() {
return {
templateUrl: '../../partials/header.html',
link: function(scope, element, attrs){
scope.breadcrumbs = attrs.breadcrumbs
}
};
});
更新:
如果在 breadcrumbs
中使用插值属性(<header breadcrumbs="{{breadcrumbs}}"></header>
),上面的代码可以是这样的:
隔离范围:
myapp.directive('header', function() {
return {
scope: {
breadcrumbs: "=" //two way binding
},
templateUrl: '../../partials/header.html'
};
});
attr
link
的属性功能:
myapp.directive('header', function() {
return {
templateUrl: '../../partials/header.html',
link: function(scope, element, attrs){
scope.breadcrumbs = scope.$eval(attrs.breadcrumbs) //eval interpolation value in this scope
}
};
});
关于javascript - Angular Directive(指令) - 更改模板内的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35195957/