gpt4 book ai didi

javascript - AngularJS:防止执行 ng-click

转载 作者:行者123 更新时间:2023-11-29 14:45:08 24 4
gpt4 key购买 nike

这是我正在修改的指令的伪代码。假设我有以下事件处理程序:

<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 事件吗?

最佳答案

也许类似于 this

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");
}
}]);

关于javascript - AngularJS:防止执行 ng-click,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33871436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com