我可以传递字符串和对象,但由于某些原因,当我将回调函数添加到我作为可配置选项使用的作用域对象时,Angular将它们取出。如何将函数作为参数传递给AngularJS指令?
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/
感谢您的帮助。
作为一个更新,我发现,如果我' console.log($ scope.options)'在'DemoCtrl'中,obj包含函数。 –