如何将函数作为参数传递给AngularJS指令?

时间:2014-03-31 17:03:38

标签: javascript angularjs angularjs-directive

我可以传递字符串和对象,但出于某种原因,当我将回调函数添加到我用作可配置选项的范围对象时,Angular会将它们删除。

HTML:

<div ng-controller="DemoCtrl">
    scope.options = {{ options }}
    <br><br>
    <div my-directive="{{ options }}"></div>
</div>

JS:

var app = angular.module('demo2', []);

app.controller('DemoCtrl', function($scope) {
    $scope.options = {
        test_str: 'test',
        init_cb: function() {
            alert('custom init callback');
        },
        apply_cb: function() {
            alert('custom apply callback');
        }
    };
});
app.directive('myDirective', ['$parse', function($parse) {
    function link(scope, element, attrs) {
        var options = attrs.myDirective;
        scope.init(options);
    }

    return {
        restrict: 'A',
        transclude: true,
        link: link,
        controller: ['$scope', function($scope) {
            $scope.defaults = {
                init_cb: function() {
                    alert('default init callback');
                },
                apply_cb: function() {
                    alert('default apply callback');
                }
            };
            $scope.settings = {};

            $scope.init = function(options) {
                $scope.settings = $.extend({}, $scope.defaults, $scope.options);

                // init cb.
                $scope.settings.init_cb();

                // apply cb.
                $scope.settings.apply_cb();
            };
        }]
    };
}]);

这是一个小提琴:http://jsfiddle.net/revolunet/pHZNY/

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

当您需要将实际变量传递到范围内时,您正尝试使用attr,它只能是一个字符串:

var app = angular.module('demo2', []);

app.controller('DemoCtrl', function($scope) {
    $scope.options = {
        test_str: 'test',
        init_cb: function() {
            alert('custom init callback');
        },
        apply_cb: function() {
            alert('custom apply callback');
        }
    };
});
app.directive('myDirective', ['$parse', function($parse) {


    return {
        restrict: 'A',
        transclude: true,
        scope: { //use scope to pass in variables
            options: '=myDirective'
        },

        controller: ['$scope', function($scope) {


            $scope.defaults = {
                init_cb: function() {
                    alert('default init callback');
                },
                apply_cb: function() {
                    alert('default apply callback');
                }
            };
            $scope.settings = {};

            $scope.init = function(options) {
                $scope.settings = angular.extend({}, $scope.defaults, $scope.options);

                // init cb.
                $scope.settings.init_cb();

                // apply cb.
                $scope.settings.apply_cb();
            }();
        }]
    };
}]);