2014-04-16 30 views
0

我想創建基於變量的HTML,我創建了一個指令,並稱爲「節點」,我想用它作爲模板來生成標記,基於什麼屬性傳遞到指令。然而角度不會渲染變量的標記?我知道有一種方法可以做到這一點我已經看到了一些關於如何使用編譯服務的教程,但它不是我所需要的。編譯服務與角

這裏是我的標記

<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8" /> 
    <title>My ng repeatStart</title> 
</head> 
<body ng-controller="AppCtrl"> 
    <node type="div" text="20"> 

    </node> 

</body> 
</html> 
<script src="download/angular/angular.min.js"></script> 
<script src="download/angular-sanitize/angular-sanitize.min.js"></script> 
<script> 
    var app = angular.module('repeatStart', []); 

    angular.element(document).ready(function(){ 

     angular.bootstrap(document.querySelector('body'), ['repeatStart']); 

    }); 

    app.directive("node", function(){ 

     return { 

      restrict:"E", 
      controller:"AppCtrl", 
      scope:{type:"@", text:"@"}, 
      link:function(scope, element, attr, ctrl){ 
       console.log(scope.type); 
       console.log(scope.text); 
      }, 
      template:"<{{scope.type}}>{{scope.text}}</{{scope.type}}>" 

     } 

    }) 


    function AppCtrl($scope, $compile){ 

     $scope.elements = [ 
      { 

      type:"range", 
      text:"Lorem ipsum dolor sit" 
      }, 
      { 
      type:"div", 
      text:"Lorem ipsum dolor sit" 
      }, 
      { 

      type:"div", 
      text:"Lorem ipsum dolor sit" 
      }, 
      { 
      type:"range", 
      text:"Lorem ipsum dolor sit" 
      }, 
      { 
      type:"range", 
      text:"Lorem ipsum dolor sit" 
      }, 
     ]; 

    } 
</script> 

在javacript線 - 模板: 「< {{scope.type}}> {{scope.text}}」 不會編譯爲一個div範圍.text和scope.type變量不會顯示爲標記?

+0

如果你沒有字符串插值的話,它會起到同樣的作用嗎? '「<」+ scope.type +「>」+ scope.text +「」' – adrichman

+0

我意識到範圍是不必要的,我嘗試過,但我會這樣工作並看看是否有效。 – Jesse

+0

我想它的工作。 – adrichman

回答

1

也許這樣?

app.directive("node", function(){ 

    return { 

     restrict:"E", 
     controller:"AppCtrl", 
     scope:{type:"@", text:"@"}, 
     link:function(scope, element, attr, ctrl){ 
      console.log(scope.type); 
      console.log(scope.text); 

      var htmlText = '<' + scope.type + '>' + scope.text + '</' + scope.type + '>'; 
      element.replaceWith(htmlText); 

     } 

    } 

}); 
+0

該作品我認爲這可能會完成這項工作謝謝。 – Jesse