AngularJS -将点击事件绑定到元素
AngularJS - Bind click event to element
我将以下部分插入到ng视图中。我只粘贴了部分中相关的部分。
<tr ng-repeat="group in groups">
<td><a href="" class="restaurant-group-edit" create-link>{{ group.name }}</a></td>
<td>{{ group.members.length }}</td>
<td>{{ 5 }}</td>
<td style="text-align: right">
<span class="pseudo-select enhanced-select ps-settings">
<select class="enhanced-select ps-settings restaurant-group-select" restaurant_group_id="1">
<option value="actions">Actions</option>
<option value="edit">Edit</option>
<option value="edit">Restaurants</option>
<option value="delete">Menus</option>
<option value="edit">Delete</option>
</select>
<span class="es-label">Actions</span>
<span class="icon"></span>
</span>
</td>
</tr>
我想为上面的每个锚元素绑定一个click事件。我已经尝试了一个名为create-link的自定义指令。在我的app.js文件中,我有以下代码:
adminApp.directive("create-link", function($location, $timeout, $rootScope) {
console.log("I fired the directive!");
return {
restrict: "A",
link: function(scope, element) {
$timeout(function(){
element.on("click", function(e) {
console.log("Clicked!");
});
});
}
};
});
但是,事件永远不会被绑定。事实上,"我触发了指令!"从未真正写入到控制台。我遗漏了什么?将事件绑定到加载视图时创建的DOM元素似乎是一个常见的用例。肯定有一个简单的方法去做这件事。
谢谢你的帮助。
安德鲁将js中的指令名改为view部分中声明的驼角格式的指令名:
adminApp.directive("createLink", function($location, $timeout, $rootScope) {
console.log("I fired the directive!");
return {
restrict: "A",
link: function(scope, element) {
$timeout(function(){
element.on("click", function(e) {
console.log("Clicked!");
});
});
}
};
});