简体   繁体   中英

AngularJS - Angular way of binding on parent to trigger child

I have the following markup:

<div class="parent">
    <div class="child">

and I have two directives, one for parent and one for child . Now, on an event (say click) on parent , I want something to happen on child (say gets a click).

The jQuery way of doing this would be:

app.directive('parent', function()
{
    return {
        restrict: 'C',
        link: function(scope, element, attrs)
        {
            element.bind('click', function()
            {
                element.find('.child').click();
            });
        }
    }
}   

And if I am not mistaking, the Angular way would be to change a scope in parent , and $watch for it in child:

app.directive('parent', function()
{
    return {
        restrict: 'C',
        link: function(scope, element, attrs)
        {
            scope.childEvent = false; 

            element.bind('click', function()
            {
                scope.childEvent = true;
            });
        }
    }
}   

app.directive('child', function()
{
    return {
        restrict: 'C',
        link: function(scope, element, attrs)
        {
            scope.$watch('childEvent', function(value)
            {
                if (value) element.click();
            })
        }
    }
}   

Can someone tell me which method is better, and why? The first method is for sure shorter, but it seems everyone says that the Angular way is the second method (so that I don't use jQuery). I want to know what problems could arise if I use the jQuery way.

I think, the second variant is "the angular way" of solving your problem. This one is (if you look from the view of an angular developer) the solution which gets along without manipulating the DOM manualy. In my opinion that's the main idea of AngularJS: stop manipulating the DOM manualy - let Angular do that for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM