2016-03-04 20 views
0

我對CanJS非常熟悉,並且有點像您可以在HTML元素上實例化自定義Web窗口小部件的想法,現在我們有一個對象,我們可以向其發送消息(調用其上的方法):在AngularJS中,你如何使一個指令成爲一個對象,以便你可以「傳遞消息」給它(調用它的方法)?

lightbox.popUp(); 

reviewStars.setStars(3.5); 

怎麼可能在AngularJS做什麼?在製作指令並將其設置爲HTML元素或將指令用作HTML元素之後,您如何執行上述操作(如OOP中的操作,或Smalltalk如何執行操作) - 將消息發送到特定的對象?

我能想到的辦法,如:

<review-stars api="ctrl.reviewStarAPI"></review-stars> 

,然後爲reviewStar指令,這樣做:

scope: { api: "=" } 
link: function(scope, elem, attrs) { 
    // first define some functions 
    scope.setStars = function(n) { ... }; 

    // and then set it to the api object: 
    scope.api.setStars = scope.setStars(); 
} 

,然後在控制器,做

vm.reviewStarAPI.setStars(3.5); 

但這有點麻煩,而且有點特別。它總是需要一個控制器......但是,我想我們可以使用1個控制器和主程序並實例化一堆對象,然後以這種方式調用它們上的方法。

除了上面的方法之外,還有什麼方法可以實現?

+0

看到一個類似的問題已經回答[這裏](http://stackoverflow.com/questions/16881478/how-to-call-a-method-defined-in-an-angularjs-directive)。 –

回答

0

模塊化方法是創建一個名爲reviewStars的指令。該指令應該有一個表示星級的參數。

例如: <review-stars rating="3.5">

您將創建一個使用類似以下內容:

angular.module('myAngularModule', []) 
.directive('reviewStars', function() { 
    return { 
    restrict: 'E', 
    scope: {}, 
    bindToController: { 
     rating: '@' 
    }, 
    link: function(scope, elem, attrs) { 
     // instantiate the lightbox code here 
    }, 
    controller: function() { 
     var vm = this; 
     // controller code goes here (e.g. the onClick event handler) 
    }, 
    controllerAs: 'ctrl', 
    templateUrl: 'review-stars.html' // the HTML code goes in this file 
    }; 
}); 

退房Rangle的NG-課程(https://github.com/rangle/ngcourse)或角文檔(docs.angularjs.org)爲更多關於指令。

相關問題