如何在角度js中创建自定义输入场

时间:2016-01-11 21:08:41

标签: javascript angularjs angular-ngmodel

我一直在研究一个自定义输入包装器,它可以添加错误文本处理等功能。问题是我无法重置模型值,从检查外部范围在重置时更新的范围。指令的内部范围没有,我不确定原因。

从范围更改指令中的ng-model监视。$ watch(ngModel,function(){到范围。$ watch(' ngModel',function(){导致重置工作但是然后当viewValue无效时,重置不起作用,重置也应该适用于这种情况。

我做错了什么吗?下面的代码重新解决了这个问题。



var app = angular.module('app', []);
app.directive('myInput', function() {
  return {
      restrict: "E",
      require: "ngModel",
      template: $('#myInput').html(),
      scope: {
        "ngModel": "=",
        "name": "@",
        "type": "@",
        "label": "@",
        "errorLabel": "@",
        "placeholder": "@"
      },
      link: function(scope, element, attributes, ngModel) {

        scope.$watch('ngModel', function() {
          scope.value = scope.ngModel;
          console.log('got value: ' + scope.value);
        });
        scope.$watch('value', function() {
          if(scope.value) {
            ngModel.$setViewValue(scope.value);
          }
        });
      }
  };
});

app.controller('user', ['$scope', function($scope) {
  $scope.currentUser = {
    email: "person@site.com"
  };
  $scope.resetUser = function() {
    console.log('resetting user');
    console.log($scope.user);
    $scope.user = angular.copy($scope.currentUser);
    console.log($scope.user);
  };
  $scope.submitUser = function(user) {
    console.log('submitting user');
    console.log(user);
  };
  $scope.resetUser();
}]);

.error {
  color: red;
}
.my-input {
  border: 5px solid transparent;
}
.ng-invalid.my-input {
  border: 5px solid red;
}

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script type="text/html" id="myInput">
    <ng-form name="thisForm">
      <label
        ng-class="{error: thisForm.$invalid}"
        for="{{name}}"
        ng-bind="thisForm.$valid ? label : errorLabel"></label></br>
      <input
        class="my-input"
        name="{{name}}"
        type="{{type}}"
        placeholder="{{placeholder}}"
        ng-model="value"></input>
    </ng-form>
  </script>
  
</head>
<body ng-app="app">
  <div ng-controller="user">
    <ng-form name="userForm">
      <my-input
        type="email"
        ng-model="user.email"
        error-label="Enter a valid Email"
        label="Email"
        placeholder="Enter an Email"
        name="Email"></my-input>
      </br>
      <button ng-click="resetUser()">Reset</button>
      <button ng-click="submitUser(user)" ng-disabled="userForm.$invalid">Submit</button>
    </ng-form>
  </div>
  
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

如果你的剩余问题是当你的输入无效时你的观察者没有触发(没有通过Angular电子邮件测试),那么因为如果输入,Angular不会更新你的模型没有通过验证。请参阅this issue进行比较。

无论如何,我建议使用Angular的ngMessages指令来显示和隐藏输入的错误消息。看起来你正在尝试构建已经开箱即用的东西。