2014-10-28 74 views
2

雖然與CoffeeScript的創建AngularJS指示我使用這種方法:使用的CoffeeScript在AngularJS指令控制器類

angular 
.module('MyApp', []) 
.directive 'myDirective', -> 
restrict: 'E' 
controllerAs: 'ctrl' 
controller: -> 
    new class 
    constructor: -> 
     @value = 3 

該代碼可以使用角1.2.14- jsbin - 但與1.3.0- jsbin沒有。我在控制檯中沒有任何錯誤,只是它什麼都不做。看起來控制器是空的對象。

+0

這對我來說很好:http://stackoverflow.com/questions/27172394/javascript-doest-convert-angular-ui-datepicker-date-to-utc-correctly/29030439#29030439 – frhd 2015-03-13 22:32:36

回答

5

我在這個線程幾乎回答了同樣的問題:AngularJS + Coffeescript - 'Hello World' directive not working。我喜歡將我的Angular對象保存爲適當的CoffeeScript類。關鍵是將new Directive()包裝在功能塊內。

class MyDirective 
    constructor: (myService) -> 
     // Constructor stuff 
     @controller = MyController 
     @controllerAs = 'ctrl' 
    restrict: 'E' 
    replace: true 
    scope: 
     attributeStuff: '=' 
    link: (scope, element, attr) -> 

angular.module('my_module').directive 'MyDirective', (myService) -> 
    new MyDirective(myService) 
+0

用你的方法吧似乎不可能使用'controllerAs'語法。 – Gpx 2014-10-29 10:18:18

+0

@Gpx我更新了我的答案,控制器和控制器As – 2014-11-10 15:28:08

+0

我明白了,但我仍然不明白這樣做的好處。 – Gpx 2014-11-11 14:14:54

0

我做了一些進一步的研究:看起來在Angualar 1.3.0中,如果您使用controllerAs Angular將採取controller並執行new就可以了。所以這段代碼解決了這個問題:

angular 
.module('MyApp', []) 
.directive 'myDirective', -> 
restrict: 'E' 
controllerAs: 'ctrl' 
controller: class 
    constructor: -> 
    @value = 3 
0

我使用用於定義我的控制器,CoffeeScript的類和它們連接到該指令(在CoffeeScript中定義)與controllerAs所以可以在模板訪問類的屬性和方法的圖案。我還使用控制器提供程序定義了這些類。這在1.2.15的角度工作很好,但是當我更新到1.3.6時崩潰了。

經過多次調試,我意識到angular不再自動將由coffeescript類返回的對象實例放到範圍中。解決方法是非常簡單的:手動將示波器上的實例化類對象,如下顯示:

myModule.directive 'cePageHeader', -> 
    restrict: 'A' 
    templateUrl: 'shared/ce-page-header.tpl.html' 
    replace: true 
    scope: true 
    controller: 'CePageHeaderDirectiveCtrl as cePageHeaderDirCtrl' 

cePageHeaderDirectiveModule.controller 'CePageHeaderDirectiveCtrl', 
(UserModel, $scope) -> 
    $scope.cePageHeaderDirCtrl = 
    new class CePageHeaderDirectiveCtrl 
    constructor: -> 
     @user = UserModel 

    goHome: -> 
     console.log "Do something to go home" 

此前,該功能僅返回由類創建的對象。添加此一個固定的問題符合1.3.6:

$scope.cePageHeaderDirCtrl = 

順便說一句,在模板我可以訪問我的類對象是這樣的:

<a class="navbar-brand" ng-click="cePageHeaderDirCtrl.goHome()"> 
    Go Home 

沒有手動分配到$範圍,$ scope.cePageHeaderDirCtrl = {},一個空對象。

相關問題