这是我正在修改的指令的伪代码。假设我有以下事件处理程序:
<a my-link ng-click="foo()" foo-check="fooCheck"></a>
angular.module('linkModule')
.directive('mylink', function () {
return {
restrict: 'A',
scope: {
fooCheck: '='
},
link: function link ($scope, $element) {
// bar method has some vital function
// for this directive`s functionality and must be run
// ONLY if certain conditions are met.
var bar = function bar () {
console.log('Executing bar');
};
$element.on('click', function (e) {
e.preventDefault();
// Validate something here
var mustContinue = $scope.fooCheck();
if ( mustContinue ) {
bar();
} else {
// Cancel ng-click here
}
});
}
};
});
因此,我的问题是:我可以阻止从指令的链接事件侦听器执行ng-click事件吗?
也许是这样的?
HTML
<a my-link ng-click="foo" foo-check="fooCheck" text="Click me!"></a>
JavaScript
var myApp = angular.module('myApp',[])
.directive('myLink',[function () {
return {
restrict: 'A',
scope: {
fooCheck: '=',
ngClick: '=',
text: '@'
},
template: '<div ng-click="click($event)">{{text}}</div>',
controller: function ($scope) {
var bar = function bar () {
console.log('Executing bar');
};
$scope.click = function(evt){
var mustContinue = $scope.fooCheck();
if (mustContinue) {
bar();
$scope.ngClick();
}
}
}
};
}]);
myApp.controller("myController",["$scope", function($scope){
$scope.fooCheck = function(){
return true;
}
$scope.foo = function(){
console.log("Foo executed");
}
}]);
您可以在ng点击中执行比较表达式,并使用标志检查true或false。如果它是真的,ng-click将处于活动状态,否则它将被禁用。
示例:如果hasBackground=true,则执行展开函数。
<i style="cursor: pointer" class="fa fa-expand fa-3x" ng-click="hasBackground || expand()"></i>
希望有助于好运。
如果
e.stopPropagation()
对您有效。