2014-09-21 68 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

相关问题