2013-07-05 49 views
2

我今天开始使用CoffeeScript和AngularJS,注意到没有大量关于如何使用CoffeeScript来正确编写AngularJS的文档或示例。我自己的实验似乎没有奏效。作为一种教学方法,有人能指出我为什么这是小提琴不起作用吗?Angular JS + CoffeeScript + JSFiddle:代码不起作用

http://jsfiddle.net/dralexmv/8km8x/4/

它声称的InventoryModule没有定义。虽然我已经在第一行中宣布了它。

这是HTML:

<div ng-app='InventoryModule' ng-controller='InventoryController'> 
<table> 
    <tr ng-repeat='item in items'> 
     <td>{{item.title}}</td> 
     <td>{{item.price | currency}}</td> 
    </tr> 
</table> 

这是CoffeeScript的:

inventoryModule = angular.module 'InventoryModule', [] 

inventoryModule.factory 'Items', -> 
    items = {} 
    items.query -> [ 
     {title: 'Table', price: '5'}, 
     {title: 'Chair', price: '10'} 
    ] 
    items 

inventoryModule.controller 'InventoryController', ($scope, Items) -> 
    $scope.items = Items.query 
+0

J当选择Angular作为框架时,SFiddle会自动将其添加到标记中。 –

回答

5

你的代码包含以下

items.query -> [{title: 'Hello', price: '5'}] 

翻译为:

var items = {}; 
    items.query(function() { // Items has no method query 
    return [{ 
     title: 'Hello', 
     price: '5' 
     }]; 
    }); 

你的意思,是定义一个成员作为一个函数,所以它应该是:

items.query =() -> [{title: 'Hello', price: '5'}] 

翻译为:

var items = {}; 

    items.query = function() { 
    return [{ 
     title: 'Hello', 
     price: '5' 
     }]; 
    }; 

这是你的意思:)

fiddle

+1

我明白了。 Tricky CoffeeScript语法我仍然习惯。 –

+0

@AlexanderVentura我很高兴我能帮上忙。如果它帮助我完成了,并且看到了AngularJS + CoffeeScript开发并且它非常好:) –

+0

最后一件事情是,当我将'$ scope.items'改为'$ scope.items = Items.query'时,页面仍然会不解析。这是为什么? –