【发布时间】:2014-05-11 05:04:41
【问题描述】:
我有一个这样的控制器:
angular.module('main', []).controller('mainCtrl', function ($scope) {
$scope.doStuff = function (cb) {
// Do some stuff.
cb();
};
});
我有一个这样的指令:
angular.module('action-bar', []).directive('actionBar', function () {
return {
restrict: 'EA',
replace: true,
template: '<h1>test</h1>',
scope: {
doStuff: '&'
},
link: function (scope, element, attrs) {
scope.doStuff(function () {
alert('callback executed');
});
}
};
});
这里是标记:
<div ng-app="main">
<div ng-controller="mainCtrl">
<div ng-action-bar></div>
</div>
</div>
我可以调用doStuff 就好了,但是cb 参数始终是undefined,即使我传入一个匿名函数作为回调。我在这里做错了什么?
【问题讨论】:
-
您是否真的将
doStuff属性传递给了HTML 中的actionBar指令?您没有向我们提供您如何使用它的示例。快速浏览一下,我认为您需要在 HTML 中添加doStuff="doStuff()".. 或者创建一个 jsfiddle 以便我们更好地查看它 -
@JoseM 抱歉,我遗漏了标记。该指令包含在由
mainCtrl控制的元素中。因此doStuff函数从控制器作用域继承到隔离作用域中。 -
@Stewie 这不是重复的,因为我不想通过
attrs传递任何东西。我只是想从链接函数中将参数传递给父范围方法。
标签: javascript angularjs scope angularjs-directive angularjs-scope