2014-09-21 71 views
1

我試圖在控制器上創建一個指令。該指令將創建一個從djangorestframework返回的項目表。控制器不是一個函數,得到了undefined

controller.js:

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

expensesApp.controller('ShoppingListController', ['$scope', '$http', 
    function($scope, $http){ 

    $http(
     { 
      method: 'GET', 
      url: '/items/?format=json' 
     }) 
     .success(function(data, status, headers, config) { 
      $scope.items = data; 
     }) 
     .error(function(data, status, headers, config) { 
    }); 

}]); 

directive.js

angular.module('expensesApp', []) 
    .directive('shoppingList', function() { 
     return { 
      restrict: 'A', 
      templateUrl: 'http://localhost:8000/static/angular/partials/shopping-list.html', 
      controller: 'ShoppingListController' 
     }; 
    }) 

的部分由指令拉進:

購物-list.html

<table class="table table-striped table-condensed"> 
    <thead> 
     <tr> 
      <th>ID</th> 
      <th>NAME</th> 
      <th>SHOP</th> 

     </tr> 
    </thead> 

    <tbody> 
     <tr ng-repeat="item in items"> 
      <td>[[ item.id ]]</td> 
      <td>[[ item.name ]]</td> 
      <td>[[ item.shop ]]</td> 
     </tr> 
    </tbody> 
</table> 

和我定義應用程序和控制器的主要html頁面。

items.html

... 
<div class="container" ng-app="expensesApp"> 
     <div class="row"> 

      <div class="col-md-6" ng-controller="ShoppingListController"> 
       <div shopping-list></div> 
      </div> 

     </div> 
</div> 
... 

表中的部分標題是被拉進頁面,但它不執行$ http和獲取的物品應該彌補的內容表。我得到ShoppingListController not a function, got undefined

如果我不將表分成一個指令,一切正常。所有項目都會返回,並且在控制檯中看不到錯誤。

任何人有任何想法我做錯了什麼?

回答

1

您在創建指令時重新定義模塊。它應該是:

angular.module('expensesApp') 
.directive('shoppingList', function() { 
    return { 
     restrict: 'A', 
     templateUrl: 'http://localhost:8000/static/angular/partials/shopping-list.html', 
     controller: 'ShoppingListController' 
    }; 
}); 

如果傳遞數組作爲第二個參數模塊的方法angular.module('expensesApp', []),角而不在它ShoppingListController控制器創建一個新的模塊。您應該使用getter語法angular.module('expensesApp')來檢索以前創建的模塊。

+0

就是這樣!很簡單。 – puffin 2014-09-21 17:30:10

相關問題