我不建议这样做,但您可以覆盖该ngClick
指令以执行您正在寻找的操作。这不是说,你应该。
考虑到原始实现:
compile: function($element, attr) {
var fn = $parse(attr[directiveName]);
return function(scope, element, attr) {
element.on(lowercase(name), function(event) {
scope.$apply(function() {
fn(scope, {$event:event});
});
});
};
}
我们可以这样做来覆盖它:
// Go into your config block and inject $provide.
app.config(function ($provide) {
// Decorate the ngClick directive.
$provide.decorator('ngClickDirective', function ($delegate) {
// Grab the actual directive from the returned $delegate array.
var directive = $delegate[0];
// Stow away the original compile function of the ngClick directive.
var origCompile = directive.compile;
// Overwrite the original compile function.
directive.compile = function (el, attrs) {
// Apply the original compile function.
origCompile.apply(this, arguments);
// Return a new link function with our custom behaviour.
return function (scope, el, attrs) {
// Get the name of the passed in function.
var fn = attrs.ngClick;
el.on('click', function (event) {
scope.$apply(function () {
// If no property on scope matches the passed in fn, return.
if (!scope[fn]) {
return;
}
// Throw an error if we misused the new ngClick directive.
if (typeof scope[fn] !== 'function') {
throw new Error('Property ' + fn + ' is not a function on ' + scope);
}
// Call the passed in function with the event.
scope[fn].call(null, event);
});
});
};
};
return $delegate;
});
});
然后你会像这样传递你的函数:
<div ng-click="func"></div>
相对于:
<div ng-click="func()"></div>
jsBin:http: //jsbin.com/piwafeke/3/edit
就像我说的那样,我不建议这样做,但这是一个概念证明,向您展示,是的 - 您实际上可以覆盖/扩展/增强内置角度行为以满足您的需求。无需深入挖掘原始实现。
如果你决定走这条路,请小心使用它(虽然这很有趣)。