Search code examples
javascripthtmlangularjsdomangularjs-module

AngularJs - Module defined but still gets "not available" error


I'm trying to build password matching mechanism using angular directive and seems like I'm missing something. I defined ng-app and ng-controller but I still get an error message stating the the module is not defined.

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

Solution

  • You're loading your library script at the wrong time. In your JSFiddle example, change onLoad to No Wrap - in <head> (for blocking) or No Wrap - in <body>. This will ensure Angular has loaded appropriately and we are okay to write our code.

    JSFiddle Link - updated fiddle


    Check out this answer: When do you put Javascript in body, when in head and when use doc.load? [duplicate] which I found quite straightforward on external library script loading placement. Moving forward, it'll be the norm, at least when crafting JSFiddle examples.