简体   繁体   中英

Callback function in an angular directive

I want to have a call back function on a directive I wrote, without creating an isolated scope. The directive simply makes the element resizeable, and thus doesn't need a separate scope (and it's desirable NOT to have isolated scope in this case, I think).

What is the best way to do this? I tried,

.controller("MyController", function ($scope) {
    $scope.myFunc = function () {
        console.log("test");
    };
})
.directive('resizeable', function ($document, $parse) {
    return function (scope, element, attr) {
        var func = $parse(attr.onFunc);
    }
 }

with

<div class="main" resizeable="" on-Func="myFunc()">

How to do this?

Try this JSFiddle .

You're close, here is what I'd do:

.directive('resizeable', ['$document', '$parse', function ($document, $parse) {
    return {
      link: function ($scope, $element, $attrs) {
        var func = $parse($attrs.resizeable);

        // do stuff...

        func($scope);
       }
    };
 }]);

And the HTML would be:

<div data-resizeable="myFunc()"></div>

Here is a working demo: http://plnkr.co/edit/as6Tylj0zPpjVsUaDDC6?p=preview

on-Func="myFunc"

Without parenthesis. And in the directive:

var func = scope[attr.onFunc];

The directive is in the same scope as the controller. So you can directly refernece the function.

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