孤立范围问题

Isolated scope issue

在 angular 上使用隔离范围时我几乎没有专业知识,但我发现了一个项目的东西,我用它来检查带有 Angular 指令的用户名的强度。

这是指令:

function usernameStrength() {
  return {
    require: 'ngModel',
    restrict: 'E',
    scope: {
      username: '=ngModel'
    },

    link: function(scope, elem, attrs, ctrl) {

      /** Watch password fields **/
      scope.$watch('username', function(newVal) {
        scope.strength = isSatisfied(newVal && newVal.length >= 8) +
          isSatisfied(newVal && /[A-z]/.test(newVal)) +
          isSatisfied(newVal && /(?=.*\W)/.test(newVal)) +
          isSatisfied(newVal && /\d/.test(newVal));

        function isSatisfied(criteria) {

          return criteria ? 1 : 0;

        }
      }, true);
  }
}

然后在我的 HTML (JADE) 上我有一个输入和显示和操作强度进度条的指令。

input.form-control(autocomplete="off", type='text', required='', ng-model="register.username")

标签强度 用户名强度(ng-模型="register.username")

到这里一切正常,但是如果我在控制器上添加一个对象来存储来自表单(这是一个向导)的所有数据并像这样设置输入 ng-model ng-model="register.data.username"(在 username-strength 指令上也是如此)在控制器中 data 这个对象

vm.data  = {};

指令中的 $watches 不再能够访问输入。

使用您的代码,您将用户名强度放在标签上,而您的指令仅针对名称为 'user-strength' 的元素触发。这是错误的方式,所以 $watch 不起作用。

  1. ngModel 绑定输入,select,文本区域,而不是标签。
  2. 您必须将 restrict 修改为 'A' 而不是 'E',并将其放入您的输入 [text]

Fixed

您正在尝试跟踪文本字段用户名的状态并在标签上打印诸如文本强度之类的内容。可以从这里继续学习sample. (source)