不使用指令

时间:2015-09-17 08:55:49

标签: angularjs

<body ng-controller="MyController">    
    <mydirective></mydirective>
</body>

AngularJS中是否有任何方法可以在不使用指令标记的情况下附加动态事件,因为它可能需要在html中添加其他标记。

<!DOCTYPE html>
<html ng-app="appname">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
</head>

<body ng-controller="MyController">    
    <mydirective></mydirective>
</body>

<script>

var app = angular.module('appname', []);
app.controller('MyController', function($scope){

});
app.directive('mydirective', function(){
  return {
    restrict: 'E',    
    link: function(scope, elem, attrs){
      angular.element(document).bind('mousedown', function(){
        console.log('clicked on document');
      });
    }
  }
});

</script>

</html>

1 个答案:

答案 0 :(得分:2)

当然可以。看看下面的JSFiddle。 但是,始终并且始终记住解除绑定事件,否则可能会导致内存泄漏和其他不需要的情况。

var buttonElement = angular.element('#myButton');
buttonElement.bind('click', function (e) {
    alert('This is a code bound event');
});

此外,建议使用诸如'ng-click'之类的指令,ng-mouseover',因为这些指令是由成千上万的开发人员精心开发和经过充分测试的。它将帮助您开发强大的应用程序

JSFiddle: Bind events through code&lt;&lt;根据OP的评论更新了小提琴

相关问题