2016-07-28 51 views
2

這是我的指令每次都不需要傳遞參數映射,從父範圍調用一個函數到一個指令?

function myDirective() { 
    var directive = { 
     restrict: "E", 
     templateUrl: "path/file.html", 
     scope: { 
      functionInParentScope: "&", 
     }, 
    }; 
    return directive; 
} 

這是在父範圍功能

$scope.functionInParentScope = (part, parts) -> 
    return (part & parts) > 0 

這是在父模板中的指令元素

<my-directive 
    function-in-parent-scope"functionInParentScope(part, parts)"> 
</my-directive> 

這是對一個呼叫功能從指令內:

functionInParentScope({part: a, parts: b}) 

如何在不需要每次提供參數映射的情況下調用父範圍中的函數?

我希望能夠只寫functionInParentScope(a, b)

回答

0

您需要反正有這個映射。然而,你可以做的是添加一些糖,所以你不必一直在模板

所以基本上我的意思是你可以裝飾原來的functionInParentScope綁定與它的新版本。事情是這樣的:

function myDirective() { 
    var directive = { 
     restrict: "E", 
     templateUrl: "path/file.html", 
     scope: { 
      functionInParentScope: "&", 
     }, 
     link: function(scope) { 
      scope.functionInParentScope = function(original) { 
       return function(a, b) { 
        return original({ part: a, parts: b}); 
       }; 
      }(scope.functionInParentScope); 
     } 
    }; 
    return directive; 
} 
0

如果不指定你的指令的對象scope鍵,該指令將默認使用父範圍。因此,只需刪除該密鑰並在您的指令中調用以下方法:

$scope.functionInParentScope(); 
相關問題