2015-04-27 46 views
1

我試圖在今天的角度定義我的第一個指令。這是什麼樣子:Angular指令無法編譯,無法正常工作

app.js:

var frameApp = angular.module('frameApp', [ 
    'ngRoute', 
    'frameServices', 
    'frameFilters', 
    'frameDirectives', 
    'frameControllers' 
]); 


console.log("1"); 
frameApp.directive('ngEnter', [function(){ 
    console.log("2"); 
    return { 
     link: function($scope, iElm, iAttrs, controller) { 
      console.log("3"); 
     } 
    }; 
}]); 

當網頁加載完畢後,我只看到「1」打印到控制檯上。

它在代碼中使用這樣的:

<input 
    type="text" 
    placeholder="username" 
    ng-model="username" 
    ng-enter="createUser()"> 

我的index.html是這樣的:

<!DOCTYPE html> 
<html ng-app="frameApp" ng-controller="PageCtrl"> 
<head> 
    <!-- lots of irrelevant scripts --> 
    <!-- config and initialization --> 
    <script type="text/javascript" 
     src="app/app.js"> 
    </script> 
    <script type="text/javascript" 
     src="app/app.routes.js"> 
    </script> 

    <title>{{ title }}</title> 
</head> 
<body> 

    <ng-include 
     src="'app/partials/header.html'" 
     onload="onHeaderLoaded()"> 
    </ng-include> 

    <ng-include 
     src="'app/partials/loginbox.html'" 
     ng-if="loginVisible"> 
    </ng-include> 

    <div id="content" ng-view></div> 

</body> 
</html> 

我最初試圖擺脫這一問題的工作指令:How to use a keypress event in AngularJS?

如何找出爲什麼它不起作用並修復它?

UPDATE

我發現這個問題,這是frameApp上面我的路線聲明第二個聲明。如果你有類似的問題,檢查你是否覆蓋任何模塊,因爲如果你這樣做,角度不會拋出任何錯誤。

+0

你能創建一個演示這個問題的plunkr嗎? – yarons

回答

0

您應該刪除''(空白)依賴注入這將拋出一個錯誤,你需要frameApp.directive('ngEnter', [function(){

指令

console.log("1"); 
frameApp.directive('ngEnter', [function(){ 
    console.log("2"); 
    return { 
     link: function($scope, iElm, iAttrs, controller) { 
      console.log("3"); 
     } 
    }; 
}]); 

更新(OP上述更改)

更換 frameApp.directive('ngEnter', ['', function(){

上述指令應該工作

Working Plunkr

+0

試過,沒有改變行爲。應該在以前的版本中引發錯誤?也許我必須將它移入模塊或其他東西? – steve

+0

@steve在控制檯中必須有一些錯誤。如果我使用「frameApp.directive」或「frameDirectives.directive」,出於某種原因angular拒絕拋出錯誤,請查看我的更新回答 –

+0

。如果我出於某種原因將指令附加到frameControllers,它將起作用。 – steve