AngularJS: How to pass arguments/functions to a directive?

后端 未结 3 1586
不知归路
不知归路 2020-12-08 06:29

Look at this Fiddle, what do I have to change, that the expressions in the template get evaluated using the arguments I defined in the HTML? The SAVE-button should call the

相关标签:
3条回答
  • 2020-12-08 06:56

    Just a quick note that you dont need the wrapping function save. Just call this in the template:

    '<button type="submit" x-ng-click="accept()">SAVE</button></div>',

    That transposes the function call and passes the parameters as expected.

    This simplifies code and makes it a lot easier to read.

    0 讨论(0)
  • 2020-12-08 06:57

    You can set two way data binding with property: '=' as Roy suggests. So if you want both key and value bound to the local scope you would do

    scope: {
        key: '=',
        value: '='
    },
    

    Since you are passing these values, you have access to them in your directive's controller. But in case you want to run a function in the context of the parent scope, which seems to be what you want to do with the accept attribute, then you would need to tell angular like this

    scope: {
        accept: "&"
    }
    

    Now, from your save method you could call the function passed via accept

    controller: function($scope, $element, $attrs, $location) {
        $scope.save= function() {      
            $scope.accept()
        };
    }
    

    Here's a jsfiddle

    0 讨论(0)
  • 2020-12-08 07:13
    scope: {
        accept: "&"
    }
    

    Use lowercase letters for function names, otherwise it doesn't work.

    0 讨论(0)
提交回复
热议问题