使用指令将消息放在元素的末尾。在Angular.JS

时间:2017-03-24 21:10:16

标签: javascript angularjs

我有任何复选框,我需要输入一个字符串" MESSAGE IN THE END"在这些复选框的最后。 我怎么能这样做?

     <input type="checkbox"  ng-model="my_check"  validate />
     <br>
     <input type="checkbox"  ng-model="my_check"  validate />
     <br>
     <input type="checkbox"  ng-model="my_check"  validate />
     <br>
     <input type="checkbox"  ng-model="my_check"  validate />

app.directive('validate', function ($timeout,$compile) {

 return {
    restrict: 'AE',
    require: 'ngModel', 

    link: function (scope, element, attrs, ngModel) {
                if (!ngModel){
            return;          
      }            
    ngModel.$parsers.push(function(val){
        var element_delete= angular.element( document.querySelector( '#errormy_check' ) )
                element_delete.remove();
                var newDirective = angular.element('<div id="errormy_check">MESSAGE IN THE END</div>');
                element.after(newDirective);
                $compile(newDirective)(scope);
                ngModel.$render();
        return false; 
    })
    }

  };
});

我需要这个!  我想在每次用户更改复选框的值时将此消息放在所有复选框的末尾。

enter image description here

http://jsfiddle.net/w7vy9kbt/

1 个答案:

答案 0 :(得分:0)

您要删除所有邮件元素而不是特定邮件元素。

var element_delete= angular.element( document.querySelector( '#errormy_check' ) );

它应该是,

var element_delete = element.next('#errormy_check');

var app = angular.module('app', []);

app.controller('appCtrl', function($scope) {});

app.directive('validate', function($timeout, $compile) {

  return {
    restrict: 'AE',
    require: 'ngModel',

    link: function(scope, element, attrs, ngModel) {
      if (!ngModel) {
        return;
      }
      ngModel.$parsers.push(function(val) {
        var element_delete = element.next('#errormy_check');
        element_delete.remove();
        var newDirective = angular.element('<div id="errormy_check">MESSAGE IN THE END</div>');
        element.after(newDirective);
        $compile(newDirective)(scope);
        ngModel.$render();
        return false;
      })
    }

  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section ng-app="app">
  <article ng-controller="appCtrl" class="container">
    <form class="form-horizontal well" name="form">
      <input type="checkbox" ng-model="my_check" validate />
      <br>
      <input type="checkbox" ng-model="my_check" validate />
      <br>
      <input type="checkbox" ng-model="my_check" validate />
      <br>
      <input type="checkbox" ng-model="my_check" validate />
    </form>
  </article>
</section>