使用未命名的链接函数

时间:2017-04-06 14:42:06

标签: javascript angularjs angularjs-directive angularjs-select2

如果没有命名链接函数,如何解析指令。更具体地说,我想装饰select-ui指令。这是他们的指令的定义:

.directive('uiSelect', function() {
    return {
             restrict: 'EA',
             scope: true,
             compile: function(tElement, tAttrs) {
                 //some code
                 return function(scope, element, attrs, ctrls){
                      //some code here
                      //how do I extend this?
                 }
             }
    }

});

这是我尝试的方式,但它给了我错误Cannot read property 'apply' of undefined,因为链接函数没有在指令中命名:

.decorator('uiSelectDirective', function($delegate, Restangular){
    var directive;
    directive = $delegate[0];
    console.log(directive, $delegate);
    directive.scope = {
        endpoint: '=',
        items: '=',
        parameters: '='
    };
    directive.compile = function() {
        return function($scope, element, attrs){
            directive.link.apply(this, arguments);
            // custom code here
        }
    };
    return $delegate;
});

修改

我尝试了建议的方法,但我遇到了问题。

.decorator('uiSelectDirective', function($delegate, Restangular){
    var directive;
    directive = $delegate[0];
    directive.scope = {
        endpoint: '=',
        items: '=',
        parameters: '='
    };


    directive.compile = function(originalCompile) {
        var args = arguments;
        return function($scope, element, attrs){
            console.log($scope); // this here is returning element instead of scope?
            return originalCompile.apply(this, args);

        }
    }(directive.compile);


    return $delegate;
});

而不是$scope我得到元素变量([div.ui-select-container.ui-select-bootstrap.dropdown])。我也有错误说没有定义tAttrs,这是主compule函数中的参数。我猜测申请不是以某种方式将参数传递给函数......

1 个答案:

答案 0 :(得分:1)

做这样的事情来扩展编译功能:

Comparable