简体   繁体   中英

angular directive to call scope method on click event

I have a grid with button that has k-grid-cancel-changes class. I would like to create a directive that will attach a click event to that button and call method on the page scope

    .directive('kGridCancelChanges', function () { 
               return {
                restrict: 'C',                
                scope: {
                    onCancelChanges: "&"
                },
                controller: function ($scope, $element, $attrs, $location) {
                    $element.click(function () {
                        $scope.onCancelChanges();
                    });
                }

            }
});

When I press button I can see $scope.onCancelChanges() fired from my directive but it never reaches function on the page scope.

 $scope.onCancelChanges = function () {
               alert('test');
            }

I would appreciate any suggestions

If you want to call a function in the scope it has to be provided like this:

<button class="k-grid-cancel-changes" on-cancel-changes="onCancelChanges()">test</button>

Demo: http://plnkr.co/edit/8vQ1wmdriGrDFGZwhqW2?p=preview

If for some reason you can't modify HTML code (say, it's rendered dynamically by Kendo) and can't add attribute, then you can only access the function to call via $parent scope reference:

$scope.$parent.onCancelChanges();

Demo: http://plnkr.co/edit/tpEEZs9VQunKXABud9yN?p=preview

And finally, if it's not principal to have isolated scope for your directive then you can simply call the function as it's the same scope:

.directive('kGridCancelChanges', function() {
    return {
        restrict: 'C',
        controller: function($scope, $element, $attrs, $location) {
            $element.click(function() {
                $scope.onCancelChanges();
            });
        }
    }
});

Demo: http://plnkr.co/edit/0OmlCJ6SgYU2GQRyBgYj?p=preview

You can create you directive like this:

app.directive('myDir', function () {

    return {
        restrict: 'C',
        scope: {
            foo: '&'
        },
        link: function(scope,elem){
            elem.on('click',function(){
               scope.foo(); 
            });
        }};

});

or use controller function instead of link if you need:

    controller: function($scope,$element){
        $element.on('click',function(){
           $scope.foo(); 
        });
    }};

Note that angular's jqLite has no element.click function.

Here is fiddle: http://jsfiddle.net/cxo77xb4/2/

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