2013-10-06 58 views
0

下面是我寫的一個簡單的指令,用於在腳本元素中插入本地存儲的HTML塊。爲什麼我的指令創建一個新的範圍?

這裏是如何使用它:

<body> 
    <div my-partial="partial1"></div> 
</body> 

<script id="partial1" type="text/html"> 
    <div> 
     <button ng-click="OK()">OK</button> 
    </div> 
</script> 

的代碼不會做我想做的,但我看到,當部分模板使用它的上面有ng-scope類指令替換元素。這讓我想到一個新的範圍被創造出來了,但這不是我的意圖。我只想插入HTML併成爲現有範圍的一部分。

這是怎麼發生的?

這裏的指令:

app.directive("myPartial", ["$compile", function ($compile) 
    { 
     var def = 
     { 
      restrict: 'A', 
      scope:false, 
      compile: function (element, attributes, transclude) 
      { 
       var tmplID = attributes.myPartial,  //Get templateID 
        markup = $("#" + tmplID).html(),  //Load partial template markup <text node> 
        partial = $("<div>").html(markup); //Stick markup text into a <div> so it'll become real DOM elements 

       partial = partial.contents();    //Don't need that outer <div> anymore 

       if (!partial.length) { throw "myPartial: " + tmplID + " not found"; } 

       //Replace this element w/ the partial template markup 
       element.replaceWith(partial); 


       //PostLink 
       //--------------------------------------------------------------------- 
       return function postLink(scope, element, attributes, modelController) 
       { 
        //Compile the partial and link it w/ the current scope 
        $compile(partial)(scope); 
       } 
      } 
     }; 

     return def; 
    }]); 

感謝任何幫助或建議代碼改進。

回答

0

我認爲問題與後鏈接功能有關。在這種情況下,我不相信我應該有一個。

這似乎工作:

{ 
     restrict: 'A', //Attribute 
     scope: false, //Don't create a new scope 

     compile: function(element, attributes, transclude) 
     { 
      //Get partial template 
      var partial = $("#" + attributes.asmPartial); 

      //Add the partial to the element 
      element.html(partial.html()); 

      //Remove the element leaving only the partial 
      element.contents().unwrap(); 
     } 
    } 
0

回答第二個問題: 您無法訪問編譯函數中的作用域。詳細原因請參閱Angular.js Repository Wiki中的「Understanding Directives」。 只需將值定期綁定到您的範圍,並根據需要使用鏈接功能修改範圍。

+0

當您設置的scope屬性是這樣的話,以** **真實的,但你肯定是這種情況時,範圍是假的? – CHS

+0

scope:true =除模板根目錄上新範圍外的所有指令實例之間的共享範圍。你可以在文檔中自己閱讀(搜索我的引用)。這就是我的理解。 – Sanjo

+2

我錯了。 「scope:false」不會創建範圍。看我的測試:http://jsfiddle.net/ZKhy5/1/ – Sanjo

相關問題