我正在尝试修改此角度库以添加新功能。 https://github.com/southdesign/angular-coverflow/blob/master/coverflow.js 这样做我需要能够将click事件附加到它正在创建的元素上。如果您查看第64-73行,您可以看到如何将元素添加到DOM。在第72行向模板添加ng-click无效。我猜这是因为angular已经开始了自举过程并且忽略了这个新创建的ng-click。这样做的正确方法是什么?我应该修改指令的模板以使用ng-repeat而不是使用vanilla javascript,然后通过查找每个元素来添加样式吗?或者有没有办法使用当前方法附加角度事件?
这是一个如何声明指令以及如何在链接(postlink)阶段初始化coverflow插件的示例。
function coverflowDirective () {
return {
restrict: 'E',
replace: true,
template: '<div class="coverflow-container"></div>',
scope: { images: "=" },
link: function (scope, element, attrs) {
// initialize
scope.coverflow = new Coverflow({
height: 320,
width: 568,
element: element,
scope: scope,
images: scope.images
}).init();
// Setup touch listeners
element.bind('touchstart', scope.coverflow.touchStart.bind(scope.coverflow));
element.bind('touchmove', scope.coverflow.touchMove.bind(scope.coverflow));
element.bind('touchend', scope.coverflow.touchEnd.bind(scope.coverflow));
// Setup mouse listeners
element.bind('mousedown', scope.coverflow.mouseDown.bind(scope.coverflow));
element.bind('mousemove', scope.coverflow.mouseMove.bind(scope.coverflow));
element.bind('mouseup', scope.coverflow.mouseUp.bind(scope.coverflow));
},
controller: function ($scope) {
$scope.logIndex = function (index) {console.log(index);};
}
};
}
这是我第一次尝试在模板中添加ng-click。
Cover.prototype.template = function () {
return '<div class="coverflow-cover" ng-click="console.log(1)" id="coverflow-cover-id-' + this.coverId + '"></div>';
};
答案 0 :(得分:0)
我在这个问题中找到了答案AngularJS - Append element to each ng-repeat iteration inside a directive。它涉及在链接函数中的元素上再次手动调用compile。虽然现在功能正常,但我仍然不确定这是否是处理此问题的最佳方法。所以我很乐意为您提供任何反馈。
function coverflowDirective ($compile) {
return {
restrict: 'E',
replace: true,
template: '<div class="coverflow-container">' +
'<div id="coverflow-scrollbar"><div id="coverflow-scrollbar-handle"></div></div>' +
'</div>',
scope: { images: "=" },
link: function (scope, element, attrs) {
// initialize
scope.coverflow = new Coverflow({
height: 320,
width: 800,
element: element,
scope: scope,
images: scope.images
}).init();
// Setup touch listeners
element.bind('touchstart', scope.coverflow.touchStart.bind(scope.coverflow));
element.bind('touchmove', scope.coverflow.touchMove.bind(scope.coverflow));
element.bind('touchend', scope.coverflow.touchEnd.bind(scope.coverflow));
// Setup mouse listeners
element.bind('mousedown', scope.coverflow.mouseDown.bind(scope.coverflow));
element.bind('mousemove', scope.coverflow.mouseMove.bind(scope.coverflow));
element.bind('mouseup', scope.coverflow.mouseUp.bind(scope.coverflow));
// recompile after template generation
$compile(element)(scope);
},
controller: function ($scope) {
$scope.logIndex = function (index) {console.log('index');};
}
};
}