您可以创建一个小小的directive
并从中获取元素。 AngularJS使它非常简单。我创建了一个名为plugin-object
的指令。 请看下面的代码。
工作Plunkr这里(http://plnkr.co/edit/ji5hT95vcDIuwpEcJlVe?p=preview)
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>myApp</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script>
var myApp = angular.module('myApp', []);
myApp.directive('pluginObject', [function ($document) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var pluginElement = element;
var pluginContainer = angular.element('#pluginContainer');
var justTest = $('#t1');
pluginElement.bind('click', function(event){
console.log(event.target);
});
pluginContainer.bind('click', function(event){
console.log(event.target);
});
justTest.bind('click', function(event){
console.log(event.target);
});
}
};
}])
</script>
<style>
#t1 { border: 2px solid gray; background-color: #f00; }
#myPlugIn { height: 100px; width: 100px;}
#pluginContainer { border: 2px solid gray; background-color: blue; width: 200px; margin: 0 auto;}
</style>
</head>
<body ng-app="myApp">
<div id="pluginContainer">
<object id="myPlugIn" plugin-object type="application/x-myPluginType">
<param name="onload" value="pluginLoaded" />
</object>
</div>
<div id="t1">TEST</div>
</body>
</html>
你甚至可以使用jQuery指令里面,你通常会做 - 看第三个选项pluginJQueryWay
,但我不会建议,因为它是不是真的有必要 - 的更多的AngularJS你认为更少,jQuery更好。 :)
还要确保你没有尝试从controller
实例化插件或将事件绑定到它 - 尝试在指令内保留任何DOM操作(最佳实践!)。
如果你得到它正确的指示将简化你的HTML和作为可重复使用的构建基块在整个应用程序不依赖于任何具体的controller
或$scope
。 这是一个美丽的东西;)
如果你要绑定一些事件中,你可以使用.bind
- 检查下面使用pluginAngularWay2
代码:
var pluginAngularWay2 = angular.element('#t1');
pluginAngularWay2.bind('click', function(event){
console.log(event.target);
});
当然你也可以绑定到其他活动,而不是仅仅的点击 .bind('change', function(){...})
等。
谢谢德沃。你能帮我设置插件对象的事件监听器吗? – bms