2014-10-09 58 views
1

我想了解角度指令中鏈接函數的執行情況。但是,我陷入了一個非常簡單的設置。以下是HTML代碼:未找到所需的角度指令

<!doctype html> 
<html ng-app="demoApp"> 
    <body> 
    <div ng-controller="DemoController" class="container"> 
     <directiveone directivetwo ></directiveone> 
    </div> 
     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script> 
     <script src="app.js"></script> 
    </body> 
</html> 

「demoApp」 在app.js定義如下:

angular.module('demoApp', []) 
.controller("DemoController", function(){ 

}) 
.directive("directiveone", function(){ 
    var linker = function(scope, element, attrs){ 
     console.log("directiveone link called"); 
    }; 
    return { 
     link : linker 
    } 
}) 
.directive("directivetwo", function(){ 
    var linker = function(scope, element, attrs){ 
     console.log("directivetwo link called"); 
    }; 
    return { 
     require: "directiveone", 
     link : linker 
    }; 
}); 

當我運行這段代碼,我得到的錯誤:

Controller 'directiveone', required by directive 'directivetwo', can't be found!

我無法找出這裏的錯誤。文件表明它可能是一個錯字,但對我來說並不明顯。

回答

1

指令默認爲僅屬性。您的directiveone指令未被拾取 - 您需要在其定義中指定restrict: 'E',或將其應用爲屬性(<div directiveone directivetwo>...

+0

是的,文檔說它默認爲E和A. https://docs.angularjs .org/api/ng/service/$ compile#-restrict-但後來我意識到這個文檔是針對v1.3.0的,我使用的是1.2.26。 – Vaibhav 2014-10-09 14:22:16