0

你好所有 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>'

谢谢你。

4

2 回答 2

1

您可以对指令使用隔离范围。考虑名称规范化。

这里是固定的JSBin

于 2015-10-29T20:45:27.283 回答
0

为您的模板创建一个指令,并将function其用作 DDO 的 compile 属性的值 请在 SO 上参考这个问题: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>');
          }
        }
      }
    });
于 2015-10-29T16:43:58.833 回答