2014-06-08 89 views
1

我在Angular的第2天,正在嘗試創建一個指令。這個想法是,我有幾張棉被的圖像要顯示,我不想重複相同的HTML。下面是一個index.html片段呈現出利用新指令和兩個「參數」的,我需要的部分:在指令中,將函數參數傳遞給html模板

<ng-samplequilt imgPath="img/t_3x3_no_sashing/jpg" 
       text="This is a 3x3 quilt without sashing."> 
</ng-samplequilt> 

這裏的部分:

<div> 
    <img src="{{imgPath}}"/> 
    <div> 
     {{text}} 
    </div> 
</div> 

最後,還有的指令(可能或可能無法正常工作):

.directive('SampleQuilt', ['imgPath','text',function(imgPath, text) { 
     return { 
      restrict: 'E', 
      templateUrl: 'partials/sample_quilt.html' 
      }; 
    }]) 

所以我明顯有點在我的頭上。我已經閱讀了大量的文檔和一些示例,但似乎沒有什麼是我正在做的。或者,也許我沒有足夠的內在化來堅持下去。

我不是在這裏尋找完整的解決方案;我不介意通過它。但我被卡住了 - 我不知道如何獲得imgPathtext,以使他們能夠部分地使用它們。

此外,指令具有嵌入式控制器。部分知道如何引用此控制器?爲什麼它能夠訪問它,因爲它被埋在指令中?

感謝您在正確的方向啓動。

編輯 -

感謝@Dalorzo我似乎有一個解決辦法。

首先,他關於定義指令範圍的想法起作用。

其次,我將該命令命名爲「SampleQuilt」。這不起作用 - 該指令什麼也沒有/無法找到。但是,當我將其重命名爲sampleQuilt時,內部名稱翻譯起作用。由於類似的原因,HTML必須參考img-path,而不是imgPath

現在這裏有三個文件。

的index.html的片段:

<sample-quilt img-path="img/t_3x3_no_sashing.jpg" 
       text="This is a 3x3 quilt without sashing."> 
</sample-quilt> 

局部:

<div> 
    <img src="{{img-path}}"/> 
    <div> 
     {{text}} 
    </div> 
</div> 

的指令:

.directive('sampleQuilt', function() { 
     return { 
      restrict: 'E', 
      scope:{ imgPath: "@", text: "@" }, 
      templateUrl: 'partials/sample_quilt.html' 
      }; 
    }) 
    ; 

EDIT 2 -

上述不起作用 - 我被瀏覽器緩存燒燬。

看來,如果這個片段在index.html是好奇...

<sample-quilt img-path="img/t_3x3_no_sashing.jpg" 
       text="This is a 3x3 quilt without sashing."> 
</sample-quilt> 

img-path屬性顯然可以拼寫三種不同的方式:img-path, 'imgPath',和img_path。所有內部轉換爲imgPath。在部分顯示值時,imgPath正確。

這裏的修正部分:根據你的榜樣

<div> 
<img src="{{imgPath}}"/> 
<div> 
{{text}} 
</div> 
</div> 

回答

1

上面我想這應該是你的意圖:

var app = angular.module('demo',[]); 

app.directive('SampleQuilt', function() { 
     return { 
      restrict: 'E', 
      scope:{ imgPath: "@", text: "@" }, 
      templateUrl: 'partials/sample_quilt.html' 
      }; 
    }); 

通過添加範圍的指令,我們創建一個「隔離範圍「。通過這種方法範圍可以通過3種方式獲取屬性:

  1. @捕獲從DOM作爲字符串值的屬性值。
  2. =將屬性評估爲父作用域的屬性。
  3. &將屬性評估爲父作用域的方法。

你可以閱讀更多關於它在這裏:

http://onehungrymind.com/angularjs-sticky-notes-pt-2-isolated-scope/

關於你HTML

  • 刪除納克,不使用它作爲你的指示的一部分,他們是由角色團隊保留的,避免他們避免衝突是很好的。你可以閱讀更多關於Angular Naming Conventions here
  • 案件(駱駝案件或帕斯卡案件)意味着在角度指示短劃線,所以SampleQuilt需要在HTML中用作sample-quilt

樣品:

<sample-quilt imgPath="img/t_3x3_no_sashing/jpg" 
       text="This is a 3x3 quilt without sashing."> 
</sample-quilt> 

關於你提到的有關指令的控制器最後一個問題。指令歸還對象有一個controller屬性,您可以使用像:

app.directive('SampleQuilt', function() { 
     return { 
      restrict: 'E', 
      controller: 'myDirController', /* <--- Controller Declaration */ 
      scope:{ imgPath: "@", text: "@" }, 
      templateUrl: 'partials/sample_quilt.html' 
      }; 
    }); 



app.controller('myDirController', ['$scope', function ($scope) { 
    // My Directive Controller implementation  
}]); 
相關問題