Javascript Ng Click在指令Compile中不起作用

Javascript Ng Click在指令Compile中不起作用,javascript,jquery,angularjs,Javascript,Jquery,Angularjs,我正在编写一个相当简单的AngularJS指令,它是一个按钮。 基本指令看起来确实像: officeButton.directive('officeImageButton', function() { return { restrict: 'E', replace: false, scope: { isDefault: '@', control: '=', label:

我正在编写一个相当简单的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.
    }
}];
然后我有了我的
链接
功能:

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函数来正确呈现按钮,如下所示:

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);
    }
},
编译:函数(元素、属性){ 变量浮动=属性['float']; //当有浮动时,确保将类“floated”添加到图像中。 if(floating){$('img',element).addClass('floatited');} //当元素上有右浮动时,请确保将iamge放置在元素后面。 //如果左浮动,则无需更改任何内容。 如果(浮动=='右'){ var imageElement=$('img',element); $(imageElement).remove(); $('span',元素).after(imageElement); } }, 但是,使用包含的
compile
功能,
ng click
不再工作。 有人怀疑我做错了什么吗


一个
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
。控制器在指令中的用途是充当
需要它的其他指令的API

我想你是想让另一个指令像那样调用
officeImageButton.onClick
?如果您这样做了,这很好,但在其他方面是多余的,只需使用
link
函数定义作用域上的元素即可

compile: function(tElem, tAttrs){

   // whatever you do now

   return function link(scope, element, attrs, ctrl){
     scope.onClick = function() {
        ctrl.onClick();
     }
}