AngularJS在ng-repeat中使用指令

时间:2015-06-23 11:24:28

标签: angularjs angular-directive

我有一个指令,我无法在ng-repeat块中使用。

这是我的指示:

ap.directive('pastDate', function() {
    return {        
        require: 'ngModel',
        link: function (scope, element, attrs, ctrl) {
            ctrl.$validators.pastDate = function(modelValue) { // 'pastDate' is the name of your custom validator ...
                var today = new Date();
                today = new Date(today.getFullYear(), today.getMonth(), today.getDate());
                return (new Date(modelValue) > today);
            }
        }
    };
});

这是HTML

<ul id="todo-list">
            <li ng-repeat="x in todo">               
                <ng-form name="repeatForm">
                    <button ng-click="open()">{{x.doc._id}}</button>
                    <label class="label label-info">{{x.doc.Name}}</label>
                    <span>{{x.doc.Address1}}</span>
                    <span>{{x.doc.Address2}}</span>
                    <span name="expDt" pastDate>Expiry Date: {{x.doc.IssueDtto}}</span>
                    <span class="help-block" ng-show="repeatForm.expDt.$error.pastDate">Valid Date Required</span>
                </ng-form>
           </li>          

(我的要求是每当x.doc.IssueDtto小于当前日期时,我想突出显示它)

非常感谢!

1 个答案:

答案 0 :(得分:1)

我会做这样的事情:

标记:

<div ng-app="myApp">
  <ul id="todo-list" ng-controller="Ctrl">
      <li ng-repeat="x in todo">               
          <ng-form name="repeatForm" highlight="">
              <button ng-click="open()">{{x.doc._id}}</button>
              <label class="label label-info">{{x.doc.Name}}</label>
              <span>{{x.doc.Address1}}</span>
              <span>{{x.doc.Address2}}</span>
              <span name="expDt" past-date="">Expiry Date: {{x.doc.IssueDtto}}</span>
              <span class="help-block" ng-show="repeatForm.expDt.$error.pastDate">Valid Date Required</span>
          </ng-form>
      </li>
  </ul>
</div>

角:

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

app.controller("Ctrl", function($scope) {
    $scope.todo = [
      {
        doc: { 
          _id: 1, 
          Name: 'Buy Food', 
          Address1: 'my address1',
          IssueDtto: '2015-06-22'
        } 
      },
      {
        doc: {
          _id: 2, 
          Name: 'Work', 
          Address1: 'my address2',
          IssueDtto: '2015-06-23'
        } 
      }
    ];
});

app.directive('highlight', function() {
    return {
        restrict: 'A',
        link: function (scope, element) {
          var today = new Date();
          today = new Date(today.getFullYear(), today.getMonth(), today.getDate());
          var issueDate = new Date(scope.x.doc.IssueDtto);
          if(today > issueDate) {
            element.addClass('highlight');
          }
        }
    };
});

Codepen:http://codepen.io/anon/pen/rVYebZ?editors=101

现在应用程序突出显示整行,如果需要,可以突出显示其他元素。

相关问题