【问题标题】:ANGULAR JS dynamic data binding to templateAngular JS 动态数据绑定到模板
【发布时间】:2015-10-29 16:33:49
【问题描述】:

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

谢谢。

【问题讨论】:

    标签: angularjs angular-template


    【解决方案1】:

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

    这里是固定的JSBin

    【讨论】:

    • 谢谢。那工作太棒了。知道如何引用数据之间有“-”吗? "banner1-Data": { "heading": "英雄测试" },
    • - 不是标识符的有效符号。
    • 谢谢。修改了数据键,去掉了'-'
    【解决方案2】:

    为您的模板创建一个指令,并使用function 作为您的 DDO 编译属性的值 请参考这个问题: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>');
              }
            }
          }
        });
    

    【讨论】:

    • 这不是我要找的。但是谢谢。我得到了答案。
    猜你喜欢
    • 2016-05-03
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    相关资源
    最近更新 更多