ANGULAR JS 动态数据绑定到模板
ANGULAR JS dynamic data binding to template
大家好Angular朋友们
我正在尝试找到一种将动态数据绑定到模板的方法。
创建了一个测试页:http://jsbin.com/jiminey/edit?html,js,output。
目前我有我的 HTML
<banner compSrc="banner1"></banner>
<banner compSrc="banner2"></banner>
和数据
$scope.bannerData ={
"banner1": {
"heading": "Hero Test"
},
"banner2": {
"heading": "Page Title (h1)"
}
};
模板
template: '<div>BannerHeading - {{bannerData.banner2.heading}}</div>'
如何根据 compSrc 属性使此模板动态化?
我正在寻找类似下面的东西所以我不必更新模板。
template: '<div>BannerHeading - {{heading}}</div>'
谢谢。
为您的模板创建一个指令,并使用 function
作为编译 属性 of DDO 的值
请在 SO 上参考这个问题:What are the benefits of a directive template function in Angularjs?
app.directive('myDirective', function(){
return {
// Compile function acts on template DOM
// This happens before it is bound to the scope, so that is why no scope
// is injected
compile: function(tElem, tAttrs){
// This will change the markup before it is passed to the link function
// and the "another-directive" directive will also be processed by Angular
tElem.append('<div another-directive></div>');
// Link function acts on instance, not on template and is passed the scope
// to generate a dynamic view
return function(scope, iElem, iAttrs){
// When trying to add the same markup here, Angular will no longer
// process the "another-directive" directive since the compilation is
// already done and we're merely linking with the scope here
iElem.append('<div another-directive></div>');
}
}
}
});
您可以为指令使用隔离作用域。考虑名称规范化。
这里是固定的JSBin
大家好Angular朋友们
我正在尝试找到一种将动态数据绑定到模板的方法。
创建了一个测试页:http://jsbin.com/jiminey/edit?html,js,output。
目前我有我的 HTML
<banner compSrc="banner1"></banner>
<banner compSrc="banner2"></banner>
和数据
$scope.bannerData ={
"banner1": {
"heading": "Hero Test"
},
"banner2": {
"heading": "Page Title (h1)"
}
};
模板
template: '<div>BannerHeading - {{bannerData.banner2.heading}}</div>'
如何根据 compSrc 属性使此模板动态化?
我正在寻找类似下面的东西所以我不必更新模板。
template: '<div>BannerHeading - {{heading}}</div>'
谢谢。
为您的模板创建一个指令,并使用 function
作为编译 属性 of DDO 的值
请在 SO 上参考这个问题:What are the benefits of a directive template function in Angularjs?
app.directive('myDirective', function(){
return {
// Compile function acts on template DOM
// This happens before it is bound to the scope, so that is why no scope
// is injected
compile: function(tElem, tAttrs){
// This will change the markup before it is passed to the link function
// and the "another-directive" directive will also be processed by Angular
tElem.append('<div another-directive></div>');
// Link function acts on instance, not on template and is passed the scope
// to generate a dynamic view
return function(scope, iElem, iAttrs){
// When trying to add the same markup here, Angular will no longer
// process the "another-directive" directive since the compilation is
// already done and we're merely linking with the scope here
iElem.append('<div another-directive></div>');
}
}
}
});
您可以为指令使用隔离作用域。考虑名称规范化。
这里是固定的JSBin