angularjs directive call function specified in attribute and pass an argument to it

后端 未结 7 746
难免孤独
难免孤独 2020-12-22 17:11

I want to create a directive that links to an attribute. The attribute specifies the function that should be called on the scope. But I also want to pass an argument to the

相关标签:
7条回答
  • 2020-12-22 17:56

    Just to add some info to the other answers - using & is a good way if you need an isolated scope.

    The main downside of marko's solution is that it forces you to create an isolated scope on an element, but you can only have one of those on an element (otherwise you'll run into an angular error: Multiple directives [directive1, directive2] asking for isolated scope)

    This means you :

    • can't use it on an element hat has an isolated scope itself
    • can't use two directives with this solution on the same element

    Since the original question uses a directive with restrict:'A' both situations might arise quite often in bigger applications, and using an isolated scope here is not a good practice and also unnecessary. In fact rekna had a good intuition in this case, and almost had it working, the only thing he was doing wrong was calling the $parsed function wrong (see what it returns here: https://docs.angularjs.org/api/ng/service/$parse ).

    TL;DR; Fixed question code

    <div my-method='theMethodToBeCalled(id)'></div>
    

    and the code

    app.directive("myMethod",function($parse) {
      restrict:'A',
      link:function(scope,element,attrs) {
         // here you can parse any attribute (so this could as well be,
         // myDirectiveCallback or multiple ones if you need them )
         var expressionHandler = $parse(attrs.myMethod);
         $(element).on('theEvent',function( e, rowid ) {
            calculatedId = // some function called to determine id based on rowid
    
            // HERE: call the parsed function correctly (with scope AND params object)
            expressionHandler(scope, {id:calculatedId});
         }
      }
    }
    
    app.controller("myController",function($scope) {
       $scope.theMethodToBeCalled = function(id) { alert(id); };
    }
    
    0 讨论(0)
提交回复
热议问题