[英]Angular directive scope evaluation with function binding ('&')
我們看到一個函數如何綁定到指令范圍的一些意外行為。 這是一個jsbin示例 。
總結一下 - 我們有一個指令,其范圍對象如下:
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上的函數。
問題是 - 我們的期望是否正確,這是一個錯誤嗎? 或者我們應該期待我們在這里看到的東西,如果是這樣,為什么呢?
不是一個合適的解決方案,但解決方法可能是將超時放入sub-dir的link函數中,如下所示:
setTimeout(function() {
$scope.result = $scope.fn();
$scope.$apply();
}, 0);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.