Access controller function by directive

Asked

Viewed 552 times

-1

hello the question and simple I have a button in my directive which of course already has an ng-click("alterardata();") the rule is that the controller calling this directive has this function by default but the problem is that I click the button and it does not work I put another button on the main page and this works

1 answer

0

Use a callback (in Portuguese, callback).

In your directive, define a scope property that will receive the callback of controller:

app.directive('exemploDiretiva', function () {
    return {
        restrict: 'AE',
        template: '<h3>Olá!</h3>',
        scope: {
            chamadaCallback: '&' // <- Define uma referência de função externa
        },
        link: function (scope, element, attrs) {
        }
    };
});

This done, set the value in view:

<exemplo-diretiva chamada-callback="meuMetodoDoController(arg1)"></exemplo-diretiva>

Note that while the definition is made in the format camelCase (chamadaCallback), the parameterization must be done in format lowercase-dash (chamada-callback).

With this done, create the method meuMetodoDoController in the controller - it will be invoked when, in the directive, you invoke callback as follows:

scope.chamadaCallback('qualquerParametroQueVoceQuiser');
  • I think I’m almost there giving this error Typeerror: Cannot use 'in' Operator to search for 'alterarPeriodo' in 1 in the template comtem(ng-click="functionPeriodo(0)"), in the panel name Directive contains (functionPeriodo: "&"), in the main page contains <panel function-period="change Memory()"></panel>

  • In function-period="change Memory()" You are passing the function result. Instead, try function-period="change Memory".

  • I’ve tried and give the same mistake I still don’t know what to do :?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.