AngularJS:使用指令OR模型选项时模型不更新

时间:2015-06-03 14:57:45

标签: angularjs angularjs-directive

我有用于检查用户密码的html的当前部分,

<div class="form-group">
    <label for="auditName" class="col-lg-4 control-label">Current Password </label>
    <div class="col-lg-8">
        <input type="password" placeholder="Current Password" 
        name="currentPassword" 
        class="form-control" 
        ng-model="currentPassword" 
        required="" 
        password-new 
        ng-model-options="{ updateOn: 'blur' }">
    </div>
    <div class="col-lg-offset-4" ng-if="form.$pending.oldPassword">checking....</div>
    <div class="col-lg-offset-4" ng-if="form.$error.oldPassword">Please create a NEW password</div>
</div>

{{currentPassword}}

我的问题是currentPassword没有更新,因此屏幕上没有显示任何内容。如果我删除模型选项并删除对新密码指令的引用,它将在您键入时显示 - 因此这些都是出于某种原因阻止模型更新值。

指令new-password看起来像这样,并且仍然是我在别处找到的基本格式,直到我正常工作,

app.directive('passwordNew', function ($timeout, $q) {
    return {
        restrict: 'AE',
        require: 'ngModel',
        link: function (scope, elm, attr, model) {
            model.$asyncValidators.oldPassword = function () {
                //here you should access the backend, to check if username exists
                //and return a promise
                var defer = $q.defer();

                $timeout(function () {
                    model.$setValidity('oldPassword', true);
                    defer.resolve;
                }, 1000);
                return defer.promise;
            };
        }
    }
}); 

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

HTML中的{{currentPassword}}超出了指令的范围。您需要链接两个范围。签出&#34;隔离指令的范围&#34;在https://docs.angularjs.org/guide/directive

在指令

上加上这样的东西
  scope: {
    currentPassword: '='
  },

示例

这就是我解决类似问题的方法

app.directive('availableEmail', [
  'dataSvc', (data:otolane.direct.IDataService) => {
    return {
      require: 'ngModel',
      restrict: 'A',
      link: function (scope, elm, attrs, ctrl) {

        ctrl.$parsers.unshift(function (viewValue) {
          ctrl.$setValidity('availableEmail', true);
          //only check the db if value is an email
          if (viewValue.length > 3 && !ctrl.$error.email) {
            data.account.checkEmail(viewValue)
              .then(() => {
                // data method resolves if email is available
                ctrl.$setValidity('availableEmail', true);
              })
              .catch(() => {
                //returns error if email is in use
                ctrl.$setValidity('availableEmail', false);
              });
          }
          return viewValue;
        });

      }
    };
  }
]);