如果使用AngularJS需要相应的表单元素,请使用星号标记标签

时间:2016-02-12 09:45:49

标签: javascript jquery angularjs

我有以下部分代码:

<form name="loginForm" ng-submit="controller.login(username, password, controller.language)" novalidate>
       <label for="username">{{"username" | translate}}</label>
       <input type="text" name="username" id="username" ng-model="username" required maxlength="15">
       <label for="password">{{"password" | translate}}</label>
       <input type="password" name="password" id="password" ng-model="password" maxlength="80" >
       <button type="submit" ng-disabled="loginForm.$invalid">{{"submit" | translate}}</button>
</form>

我正在寻找解决方案来动态标记所有相应的标签,其中包含所需的所有表格元素(无论是输入,文本区域,复选框或无线电)的星形(即必填字段),最理想的是使用AngularJS代码。

1 个答案:

答案 0 :(得分:1)

试试这个Page Layout

&#13;
&#13;
var myApp = angular.module("myApp", []);


myApp.controller("myCtrl", function($scope) {

  })
  .directive('markRequired', function() {
    return {
      restrinct: 'A',
      require: "^form",
      scope: {
        for: "@",
      },
      link: function(scope, element, attr, form) {
        scope.$watch(function() {
          return form[scope.for]
        }, function(newVal) {
          console.log(newVal);
          if (newVal.$validators && newVal.$validators.required) {
            element.addClass('required');
          }
        });
      },
    }
  });
&#13;
label.required:after {
  content: ' *';
  color: #f00;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
  <form name="loginForm" ng-submit="controller.login(username, password, controller.language)" novalidate>
    <label for="username" mark-required>{{"username" }}</label>
    <input type="text" name="username" id="username" ng-model="username" required maxlength="15">
    <label for="email" mark-required>{{"email" }}</label>
    <input type="text" name="email" id="email" ng-model="email" maxlength="15">
    <label for="password" mark-required>{{"password" }}</label>
    <input type="password" name="password" id="password" ng-model="password" maxlength="80" required>
    <button type="submit" ng-disabled="loginForm.$invalid">{{"submit" }}</button>
  </form>
</body>
&#13;
&#13;
&#13;

相关问题