2015-10-28 39 views
0

我正在教我自己Angular,我正在用localStorage製作一個小靜態應用程序。儘管試圖通過指令加載模板,但我遇到了一些障礙。我對此仍然很陌生,並希望得到任何反饋。我花了一些時間瀏覽以前的問題的答案,但沒有一個解決了我的問題。角度指令不加載模板,靜態應用程序(無服務器)

我沒有收到任何錯誤,當我檢查開發工具時,根本沒有加載該文件。我嘗試過不同的模板:和templateUrl配置,沒有任何工作。

這裏是我的指令代碼:

angular.module('dropForm', []) 
.directive('dropForm', function(){ 

    return{ 
    restrict:'E', 
    replace:true, 
    templateUrl:'drop-form.html', 

    link: function(scope, elem, attr){ 
    var dropButton = angular.element(document.querySelector('#dropButton')); 
    } 
    } 
}); 

我的文件結構是基本的,這只是一個靜態的應用程序。我有一個index.html,在同一個目錄下是drop-form.html。我的js文件和鏈接中通過腳本標籤中的index.html

這裏是我的,我所說的指令中的index.html:

<body ng-controller = "mainController"> 
    <div drop-form> </div> 
     <div class = "container main"> 
     <h1 ng-bind="$storage.toDos.length || 'All Done!'"></h1> 
     <div ng-repeat = "todo in $storage.toDos"> 
      <div style = "" class = "todo-item"> 
      <div> 
       <h5 ng-bind = "todo.text"></h5> 
      </div> 
      <i class="fa fa-trash" ng-click="destroyTodo(todo)"></i> 
      </div> 
     </div> 
     </div> 
    </body> 
</html> 

該指令模板不加載在所有的,但我有沒有erros,請幫助我瞭解我在這裏誤解了什麼。 謝謝!

+0

你已經錯過了'NG-app'指令。 –

+0

你在主應用程序中加載你的模塊嗎? – Icycool

+0

您的templateUrl應該是完整的網址到您所指的html頁面。嘗試定義如下所示的內容。 templateUrl:'http:// localhost'+'drop-form.html'。還可以嘗試根據您的項目結構將適當的文件夾添加到路徑中。 –

回答

1

首先你已經錯過了你的ng-app與名字在你的情況dropForm(在我的例子中,我將其設置爲「對myApp」),並把它添加到你的身體元素

<body ng-app="myApp" ng-controller = "mainController"> 
    <div drop-form> </div> 
     <div class = "container main"> 
     <h1 ng-bind="$storage.toDos.length || 'All Done!'"></h1> 
     <div ng-repeat = "todo in $storage.toDos"> 
      <div style = "" class = "todo-item"> 
      <div> 
       <h5 ng-bind = "todo.text"></h5> 
      </div> 
      <i class="fa fa-trash" ng-click="destroyTodo(todo)"></i> 
      </div> 
     </div> 
     </div> 
    </body> 
</html> 

Second.In你的指令,你已經使用限制「E」。它意味着你必須使用它僅作爲元素<drop-form></drop-form>「E」立場元),但你想<div drop-form> </div>工作已作爲attr.If,你必須添加也限制'A'restrict:**'AE'**或改造<div drop-form> </div><drop-form></drop-form>

,這將是你的代碼

angular.module('myApp', []) 
.directive('dropForm', function(){ 

    return{ 
    restrict:'AE', 
    replace:true, 
    templateUrl:'drop-form.html', 

    link: function(scope, elem, attr){ 
    var dropButton = angular.element(document.querySelector('#dropButton')); 
    } 
    } 
}); 
+0

非常感謝!我的錯。我很確定這個問題與templateUrl有關,我完全忽略了限制值。謝謝你指出。謝謝,經驗教訓。 – Liam