AngularJs - 已定义模块但仍然“无法使用”错误

时间:2016-04-05 16:12:44

标签: javascript html angularjs dom angular-module

我正在尝试使用角度directive构建密码匹配机制,似乎我错过了一些东西。我定义了ng-appng-controller,但我仍然收到一条错误消息,指出module未定义。

Jsfiddle here

Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to:
Error: [$injector:nomod] Module 'myApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

HTML:

<div ng-app="myApp">
  <div class="row" ng-controller='Ctrl'>
    <form name="form1">
      <div class="col-xs-12 col-sm-6 col-md-6">
        <div class="form-group">
          <input type="password" ng-model="login.password" name="password" id="password" class="form-control input-lg" placeholder="Password" tabindex="5">
        </div>
      </div>
      <div class="col-xs-12 col-sm-6 col-md-6">
        <div class="form-group">
          <input ng-model="login.verify" type="password" name="verify" placeholder="Confirm Password" nx-equal="login.password" class="form-control input-lg" tabindex="6">
          <div class="error" ng-show="form1.verify.$error.nxEqual">Passwords are not equal</div>
        </div>
      </div>
    </form>
  </div>
</div>

JS:

var app = angular.module("myApp", []);
app.controller("Ctrl", function($scope){

});
app.directive('nxEqual', function() {
  return {
    require: 'ngModel',
    link: function(scope, elem, attrs, model) {

      if (!attrs.nxEqual) {
        console.error('nxEqual expects a model as an argument!');
        return;
      }
      scope.$watch(attrs.nxEqual, function(value) {
        model.$setValidity('nxEqual', value === model.$viewValue);
      });
      model.$parsers.push(function(value) {
        var isValid = value === scope.$eval(attrs.nxEqual);
        model.$setValidity('nxEqual', isValid);
        return isValid ? value : undefined;
      });
    }
  };
});

1 个答案:

答案 0 :(得分:3)

您在错误的时间加载了库脚本。在您的JSFiddle示例中,将onLoad更改为No Wrap - in <head>(用于阻止)或No Wrap - in <body>。这将确保Angular已正确加载,我们可以编写我们的代码。

JSFiddle Link - 更新小提琴

查看this answer: When do you put Javascript in body, when in head and when use doc.load? [duplicate],我发现外部库脚本加载位置非常简单。展望未来,至少在制作JSFiddle示例时,它是常态。