javascript - AngularJs - 模块已定义但仍然出现 "not available"错误

标签 javascript html angularjs dom angular-module

我正在尝试使用 angular 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;
      });
    }
  };
});

最佳答案

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

JSFiddle Link - 更新的 fiddle


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

关于javascript - AngularJs - 模块已定义但仍然出现 "not available"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36431717/

相关文章:

angularjs - 如何使用 $broadcast 发送对象?

java - 在javascript中调用restful webservice时如何传递对象

javascript - 如何在 HTML5 Canvas 中展开模糊滤镜半径?

c# - .NET 中的 try-catch 执行 jQuery 脚本

javascript - 如何使用 Javascript 清除 HTML 上的文本框

javascript - 通过 CSS/javascript 对 div 的模糊效果?

javascript - 谷歌在 IE 中映射不需要的白线

javascript - 从 Redux 状态属性渲染 React 组件

javascript - 为 ng-model angular.js 提交表单 ng-repeat

javascript - 无法弄清楚为什么 angularJS 模块无法加载