【问题标题】:AngularJs - Module defined but still gets "not available" errorAngularJs - 模块已定义但仍然出现“不可用”错误
【发布时间】:2016-07-25 17:02:45
【问题描述】:

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

jsfiddlehere.

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;
      });
    }
  };
});

【问题讨论】:

  • 你定义控制器Ctrl了吗?
  • 你确定你在页面上引用了角度控制器和指令js 文件吗?
  • 谢谢,我做了,但忘记更新了。同样的错误。
  • @PankajParkar,整个脚本位于同一页面中的 script 标记内。
  • @undroid 你能把那个脚本加载部分添加到有问题的地方吗?

标签: javascript html angularjs dom angular-module


【解决方案1】:

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

JSFiddle Link - 更新小提琴


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

【讨论】:

  • 像往常一样忙我的朋友 :) @PankajParkar
猜你喜欢
  • 2019-07-09
  • 2019-06-01
  • 2019-11-29
  • 2017-12-20
  • 2020-04-01
  • 2019-08-06
  • 2019-01-14
  • 2021-02-05
  • 1970-01-01
相关资源
最近更新 更多