我正在编写一个相当简单的AngularJS指令,即一个按钮。基本指令确实看起来像:
officeButton.directive('officeImageButton', function() {
return {
restrict: 'E',
replace: false,
scope: {
isDefault: '@',
control: '=',
label: '@',
image: '@'
},
template: '<div class="button-wrapper" ng-click="onClick()">' +
'<a href="#" class="button image-button">' +
'<img src="{{image}}" />' +
'<span>{{label}}</span>' +
'</a>' +
'</div>',
// Reset of the code not included for readability - See below.
}
}];
在此指令中,我确实定义了一个控制器:
/**
* @description
* Provides the controller for the 'officeImageButton' control. In this controller, all the required methods and
* other information is stored.
*/
controller: ['$scope', function($scope) {
// Allows an API on the directive.
$scope.api = $scope.control || {};
/**
* @kind Click
* @name onClick
*
* @description
* This function is executed when the user click's the button itself.
*/
this.onClick = function() {
if (typeof $scope.api.onClick === 'function') { $scope.api.onClick(); }
}
}],
,然后我有我的link
函数:
link: function(scope, element, attributes, controller) {
/**
* @kind Event
* @name onClick
*
* @description
* Executes when the user click's the button.
*/
scope.onClick = function() {
controller.onClick();
}
}
由于在模板中,我确实有一个ng点击属性,因此在单击按钮时执行scope.onClick
函数。这种行为是可以预期的。
但是现在,在我的指示中,我还需要使用编译功能来正确渲染按钮,如下所示:
compile: function(element, attributes) {
var floating = attributes['float'];
// When there's floating, make sure to add the class 'floated' to the image.
if (floating) { $('img', element).addClass('floated'); }
// When there's right floating on the element, make sure to place the iamge after the <span> element.
// In case of left floating, nothing needs to be changed.
if (floating === 'right') {
var imageElement = $('img', element);
$(imageElement).remove();
$('span', element).after(imageElement);
}
},
但是,使用此compile
功能,ng-click
不再工作。在这里我做错了什么?
善意
a compile
函数的返回值是前和后link
函数,因此,当定义compile
属性时,link
属性将被忽略。而且,由于您没有在编译中返回该链接功能,因此scope.onClick
不在范围内。
要修复,您需要进行一些重构:
compile: function(tElem, tAttrs){
// whatever you do now
return function link(scope, element, attrs, ctrl){
scope.onClick = function() {
ctrl.onClick();
}
}
非主题:
另外,请注意,您无需在控制器中创建onClick
。控制器在指令中的使用是充当require
其他指令的API。
我假设您确实是要让officeImageButton.onClick
被另一个指令调用吗?如果您这样做了,那很好 - 但否则它是多余的 - 只需使用link
函数来定义范围上的元素。