4

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

1 回答 1

3

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

JSFiddle Link - 更新的小提琴


看看这个答案:你什么时候把 Javascript 放在 body 里,什么时候放在 head 里,什么时候使用 doc.load?[重复]我发现在外部库脚本加载位置上非常简单。展望未来,这将成为常态,至少在制作 JSFiddle 示例时如此。

于 2016-04-05T16:20:04.013 回答