【问题标题】:Decorating angularJS directive controller function with controllerAs syntax使用 controllerAs 语法装饰 angularJS 指令控制器函数
【发布时间】:2017-03-29 10:27:30
【问题描述】:

我正在尝试使用 $provide.decorator 更改特定供应商指令的行为。

基本指令看起来像这样:

angular
    .module('vendor.module')
    .controller('vendorCtrl', [$scope, function($scope) {
        var vm = this;

        vm.baseFunction = function() {
            //code I want to replace
        }
    }])

    .directive('vendorDir', function() {
      return {
        restrict: 'E',
        controller: 'vendorCtrl as vm',
        scope: {
          stuff: '='
        },
        bindToController: true
      }
    }

    // and this is my decorator
angular
    .module('vendor.module')
    .config(function($provide) {
        $provide.decorator('vendorDirDirective', function($delegate) {
            var directive;
            directive = $delegate[0];

            // how to override vm.baseFunction ?
            return $delegate;
        });
    }

当另一个指令启动时,我的代码成功运行,但我不确定如何替换控制器内的函数。尝试 $scope.baseFunction = function() {} 无效。

如何更改此函数的行为?

【问题讨论】:

  • 装饰器会改变一个方法的 return 值,这样你就可以在一个单独的文件中更正式地写出你的控制器,并装饰那个方法。

标签: angularjs angularjs-directive decorator


【解决方案1】:

试试这样的

var _baseFunction = scope.baseFunction;
function baseFunctionExtended() {
    _baseFunction.apply(this, arguments);
    console.log("yay, I'm modified one!");
}
scope.baseFunction = baseFunctionExtended;

这将允许调用原始函数,如果不需要,也可以不调用,并添加更多内容。下一个问题是如何达到这一点。我想尝试像上面那样扩展链接功能。

【讨论】:

    猜你喜欢
    • 2015-07-08
    • 2015-11-07
    • 2017-02-07
    • 1970-01-01
    • 2015-12-03
    • 2016-09-21
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    相关资源
    最近更新 更多