Reputation: 525
Hope you can help me with my problem. I have 2 cases:
Case #1: Fiddle, I am trying to trigger the ng-click function of the child div, when I click in the parent div (an ng-click involved also in the parent), but I am getting an error ($apply already in progress).
Controller:
function MyCtrl($scope) {
$scope.pressOnParent = function ($event) {
event.stopPropagation();
console.log("Click over the parent");
$("#child").trigger("click");
}
$scope.pressMe = function ($event) {
$event.stopPropagation();
console.log("I am being pressed");
}
}
Case #2: Fiddle, I am trying to do the same thing, but not using ng-click in the parent (but using jquery to attach the click event to it).
Controller:
function MyCtrl($scope) {
$("#parent").on("click", function (event) {
event.stopPropagation();
console.log("Click over the parent");
$("#child").trigger("click");
});
$scope.pressMe = function ($event) {
$event.stopPropagation();
console.log("I am being pressed");
}
}
My main goal is trying to get the Case #1 solved, because that is the case which is very alike to my final code in the project. Any ideas?
Thanks for the help you can give me!
Upvotes: 3
Views: 6672
Reputation: 7646
Your approach here is against Angular's declarative principles. Instead of locating the child div and clicking it within the parent callback you should be more explicit. Consider this example
function MyCtrl($scope) {
var logger = function () {
console.log("I am being pressed");
};
$scope.pressOnParent = function () {
console.log('parent clicked');
logger();
};
$scope.pressMe = function () {
logger();
};
}
Upvotes: 2
Reputation: 6187
Doing DOM manipulation inside the controller considered a bad practice and should be avoided,so instead of using JQuery you can just call the child function inside the parent function.
Example:
function MyCtrl($scope) {
$scope.pressOnParent = function ($event) {
event.stopPropagation();
console.log("Click over the parent");
$scope.pressMe($event);
}
$scope.pressMe = function ($event) {
$event.stopPropagation();
console.log("I am being pressed");
}
}
edited your fiddle: http://jsfiddle.net/choroshin/rMXrA/
Upvotes: 4