我有一个这样的 HTML 结构:
<div ng-click="test()">
<div id="myId" ng-click="test2()"></div>
<div></div>
...
</div>
目前,当我点击div
带有 id 的 id时myId
,两个函数都会被触发,但我希望只test2
触发这个函数。我怎样才能做到这一点?
我有一个这样的 HTML 结构:
<div ng-click="test()">
<div id="myId" ng-click="test2()"></div>
<div></div>
...
</div>
目前,当我点击div
带有 id 的 id时myId
,两个函数都会被触发,但我希望只test2
触发这个函数。我怎样才能做到这一点?
您需要做的就是停止事件传播/冒泡。
此代码将帮助您:
<div ng-click="test()">ZZZZZ
<div id="myId" ng-click="test2();$event.stopPropagation()">XXXXX</div>
<div>YYYYYY</div>
...
</div>
如果您的test
和test2
函数如下所示,test2
则单击myId
DIV 时您只会进入控制台。没有$event.stopPropagation()
你会在控制台输出窗口中
被test2
跟踪。test
$scope.test = function() {
console.info('test');
}
$scope.test2 = function() {
console.info('test2');
}
与汤姆的答案相同,但略有不同。
<div ng-click="test()">
<div id="myId" ng-click="test2($event)">child</div>
</div>
$scope.test2 =function($event){
$event.stopPropagation();
console.log("from test2")
}
$scope.test =function(){
console.log("from test")
}
这是基于另一个支持 ng-href 链接的问题的指令。
指示
'use strict';
var myApp = angular.module('myApp', [
'ngAnimate'
]);
/**
* @ngdoc directive
* @name myMobileApp.directive:stopEvent
* @description Allow normal ng-href links in a list where each list element itselve has an ng-click attached.
*/
angular.module('myApp')
.directive('stopEvent', function($location, $rootScope) {
return {
restrict: 'A',
link: function(scope, element) {
element.bind('click', function(event) {
// other ng-click handlers shouldn't be triggered
event.stopPropagation(event);
if(element && element[0] && element[0].href && element[0].pathname) {
// don't normaly open links as it would create a reload.
event.preventDefault(event);
$rootScope.$apply(function() {
$location.path( element[0].pathname );
});
}
});
}
};
})
.controller('TestCtrl', ['$rootScope', '$scope', 'Profile', '$location', '$http', '$log',
function($rootScope, $scope, Profile, $location, $http, $log) {
$scope.profiles = [{'a':1,'b':2},{'a':3,'b':3}];
$scope.goToURL = function(path, $event) {
$event.stopPropagation($event);
$location.path(path);
};
}
]);
<div ng-repeat="x in profiles"
ng-click="goToURL('/profiles/' + x.a, $event)">
<a stop-event ng-href="/profiles/{{x.b}}">{{x}}</a>
</div>