【发布时间】:2015-07-14 23:12:17
【问题描述】:
我正在编写一个相当简单的 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-click 属性,所以当我单击按钮时会执行 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 就不再工作了。
对我在这里做错了什么有任何不满吗?
亲切的问候
【问题讨论】:
标签: javascript jquery angularjs