我可以傳遞字符串和對象,但由於某些原因,當我將回調函數添加到我作爲可配置選項使用的作用域對象時,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包含函數。 –