【发布时间】:2015-03-06 06:38:17
【问题描述】:
我对 AngularJS 很陌生,所以我试着理解它。 因此,当您阅读最初的问题时,不要向我开枪。
我正在使用 AngularJS 开发一个应用程序。 HTML 看起来像这样:
<div id="OfficeUI" ng-controller="Office as Office">
<div class="absolute">
<div class="container application-icons icon">
<img id="{{icon.Id}}" ng-repeat-start="icon in Office.Icons" ng-repeat-end ng-src="{{icon.Icon}}" alt="{{icon.Alt}}" />
</div>
</div>
</div>
我的应用程序的控制器如下所示:
var OfficeUI = angular.module('Office');
// Defines the Office controller for the application.
OfficeUI.controller('Office', ['$http', function($http) {
// Defines required variables.
var application = this;
// Get the Json file 'application.json' that defines the application data.
$http.get('/OfficeUI.Beta/Resources/JSon/application.json')
.success(function(data) {
application.Title = data.Title;
application.Icons = data.Icons;
})
.error(function(data) {
console.error('An error occured while loading the \'application.json\' file.');
});
}]);
正如您在 HTML 中看到的,我正在根据特定 JSon 文件中的数据绑定图像元素。
现在,我希望用户能够将事件添加到给定元素(在本例中为图像)。 因此,我开发了一个 jQuery 插件,如下所示:
(function ( $ ) {
$.fn.OfficeUI = function(options) {
var settings = $.extend({
}, $.fn.OfficeUI.Defaults, options);
return this;
}
$.fn.OfficeUI.Defaults = { };
$.fn.OfficeUI.bind = function(elementSelector, bound, action) {
$(elementSelector).on(bound, function() { action(); });
return this;
};
}(jQuery));
这个插件允许我调用添加事件如下:
$(this).OfficeUI.bind("icoApplication", "click", function() {
console.log('The following element is bound.');
});
但是,该函数的第一个参数采用选择器来查找要将事件附加到的元素。但在 AngularJS 中,这不起作用,因为尚未创建元素。
谁知道如何解决这个问题? 我确实想为用户提供一种干净、简约的方式来将事件绑定到应用程序,而无需修改现有的控制器、指令、过滤器……
提前致谢。
【问题讨论】:
-
我建议查看
angular.element()的文档(如果加载 jquery,则为 jquery - 如果不加载,则为 jQLite)并建议如果您在控制器范围内进行绑定,则可以控制它在 $digest 循环see this 中发生,这允许 Angular 在绑定之前知道您在做什么并创建 - 通常,如果您要使用 Angular,请避免在 jQuery 中构建东西并使用指令或服务用角度代替。
标签: javascript jquery angularjs