2015-04-27 167 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