我们在如何将函数绑定(bind)到指令范围方面看到了一些意想不到的行为。 Here is a jsbin example .
总而言之——我们有一个具有如下范围对象的指令:
scope: { fn: '&', val: '@' }
指令显示 fn
的结果两次。首先我们在模板中显示计算结果,然后在 link
函数中显示计算结果:
<div><code>fn (&)</code>: {{fn()}}</div>
<div><code>fn result ($scope.result = $scope.fn()) </code>: {{result}}</div>
然后我们在另一个指令中使用这个作用域:
app.directive('rootDirective', function() {
function link($scope, $elem, $attrs) {
$scope.name = 'directive with scope';
}
return {
scope: 'isolate',
replace: true,
restrict: 'E',
link: link,
template: [
'<div add-scope-directive="">',
' <div ng-repeat="n in [1]">',
' <sub-dir val="{{val}}" fn="fn()" name="{{n}}"></sub-dir>',
' </div>',
' <sub-dir val="{{val}}" fn="fn()" name="{{name}}"></sub-dir>',
'<div>'
].join('\n')
};
});
在这个指令的根节点上,我们有另一个指令 add-scope-directive
。在此指令中,我们定义了 fn
- 它返回“add-scope-directive - fn”。
我们现在希望看到 fn
(“add-scope-directive - fn”)的结果在整个指令中是相同的。然而,当子指令“sub-dir”未在转发器中使用时,其链接函数的结果是不同的 - 相反,它来自 MainCtrl 上的函数。
问题是 - 我们的期望是否正确,这是一个错误吗?或者我们应该期待我们在这里看到的东西,如果是的话,为什么?
最佳答案
这不是一个合适的解决方案,但解决方法可能是在子目录的链接函数中设置超时,如下所示:
setTimeout(function() {
$scope.result = $scope.fn();
$scope.$apply();
}, 0);
关于javascript - 具有函数绑定(bind)的 Angular 指令范围评估 ('&' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24038563/