[英]Angular directive, binding click event to outside element not working
[英]Creating a modal directive, and binding click event on it in angular js
我對angularjs絕對陌生,我可能錯過了很多概念。 我正在嘗試為我的應用程序創建一個模式指令,但有一些令我煩惱的東西,那就是如何與該指令進行交互。
我正在使用yeoman,它使用以下命令生成模式指令:
yo angular:directive modal --coffee
所以我的指令目錄中有以下代碼:
angular.module('myApp')
.directive('modal', () ->
templateUrl: 'views/partials/modal.html'
restrict: 'E'
link: (scope, element, attrs) ->
console.log 'link --test'
)
現在,在我的modal.html
部分中,我插入了一個錨標記,該標記將處理單擊並向我發出警報。
<div><a href="" ng-click="foo()">Click Me</a></div>
現在我應該把foo
函數放在哪里?
我嘗試過這樣的事情,但是沒有運氣
angular.module('myApp')
.directive('modal', () ->
templateUrl: 'views/partials/modal.html'
restrict: 'E'
link: (scope, element, attrs) ->
console.log 'link --test'
controller: ($scope) ->
$scope.foo = () ->
console.log 'clicked that anchor'
)
另一個問題,我做對了嗎?我的意思是創建模態指令正確嗎? 或指令以不同的方式使用?
將foo()
放在指令控制器中效果很好。 而且您處在正確的軌道上。 推薦在Angular中使用指令進行DOM操作-因此模式對話框是指令的好用例。
確保您的html初始化Angular並使用如下指令:
<div ng-app="myApp">
<modal></modal>
</div>
這是使用您的代碼以及上面的html的有效提琴 (為了簡單起見,我直接使用了模板)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.