Angular-Rails: пользовательский фильтр не удаляет будущие даты

0

В настоящее время я внедряю AngularJs в свое приложение RoR. У меня возникла проблема с поисковым фильтром для search_blogs отображающим будущие даты через ng-repeat. У меня есть настраиваемый фильтр xFutureDates который должен отклонить любые будущие даты. Я проверил HTML в валидаторе и перепрограммировал логику AngularJs, но не решил.

HTML:

<div class="container-fluid">
  <div class="row text-center">
    <div class="col-xs-12">
      <%= link_to('Logout', {:controller => "users", :action => 'destroy'}, :method => :delete, class: "blog_home_logout" ) %>
    </div>
  </div>
</div>
<div ng-controller="BlogController">
  <div class="container-fluid">
    <div class="row text-center">
      <div class="col-xs-12 col-sm-12 col-md-12">
        <h4 class="user_session_signedInAs_txt">
        Signed in as:
        <span class="user_session_email"><%= session[:email] %></span>
        </h4>
        <h4>
        </h4>
        <h4 class="search_blogs_heading">Search Blogs</h4>
      </div>
      <div class="col-sm-2 col-md-2"></div>
      <div class="col-sm-8 col-md-8">
        <h6 class="search_blogs_label">Enter "title" or "date"</h6>
        <input type="text" class="search_blogs_input" ng-model="search_blogs" placeholder=" Title or Date" autofocus>
      </div>
    </div>
    <div class="row">
      <div class="col-sm-2 col-md-2"></div>
      <div class="col-xs-12 col-sm-8 col-md-8">
        <div class="blog_search_div" ng-repeat="blog in blogs | filter: search_blogs | xFutureDates | limitTo: 15" >
          <!-- ng-show="search_blogs" -->
          <br>
          <br>
          <a href="/blog_page?date={{blog.date}}">
            <p class="blog_search_date">{{blog.date}}</p>
            <p class="blog_search_title">{{blog.title}}</p>
          </a>
        </div>
      </div>
    </div>
  </div>
  <div class="container-fluid">
    <div class="row">
      <img class="spa_room_image" src="/assets/SpaTreatmentRoom.jpg">
    </div>
  </div>
  <div class="container-fluid">
    <div class="row text-center">
      <h4 class="recent_blogs_heading">Recent Blogs</h4>
    </div>
    <div class="row">
      <div class="col-xs-12">
        <div ng-repeat="blog in blogs | recentMonths | limitTo:10">
          <a href="/blog_page?date={{blog.date}}">
            <p class="blog_recentBlogs_date">{{blog.date}}</p>
            <p class="blog_recentBlogs_title">{{blog.title}}</p>
            <p class="blog_recentBlogs_description">{{blog.description.trunc(140)}}Read More</p>
          </a>
        </div>
      </div>
    </div>
  </div>
  <div class="container-fluid blogs_index">
    <div class="row text-center">
      <h4 class="blog_index_heading">Recent Blogs</h4>
    </div>
    <div class="row text-center">
      <div class="col-xs-12">
        <div ng-repeat="blog in blogs | recentMonths | limitTo:10">
          <a href="/blog_page?date={{blog.date}}">
            <h6 class="archives_index_blog_title">{{blog.title}}</h6>
          </a>
        </div>
      </div>
    </div>
    <div class="row text-center">
      <h4 class="blog_index_heading">Categories</h4>
    </div>
    <div class="row text-center">
      <div class="col-xs-12 col-sm-12">
        <div class="blog_category_div">
          <h6 class="blog_category_links"><a href="/blog_category_archive?category='Body Contouring'">Body Contouring</a></h6>
          <h6 class="blog_category_links"><a href="/blog_category_archive?category='Breast Reduction Liposuction'">Breast Reduction Liposuction</a></h6>
          <h6 class="blog_category_links"><a href="/blog_category_archive?category='Breast Reduction Surgery'">Breast Reduction Surgery</a></h6>
          <h6 class="blog_category_links"><a href="/blog_category_archive?category='Cosmetic Surgery'">Cosmetic Surgery</a></h6>
          <h6 class="blog_category_links"><a href="/blog_category_archive?category='Cosmetic Surgery Procedures'">Cosmetic Surgery Procedures</a></h6>
          <h6 class="blog_category_links"><a href="/blog_category_archive?category='Facelift'">Facelift</a></h6>
          <h6 class="blog_category_links"><a href="/blog_category_archive?category='Fat Grafting'">Fat Grafting</a></h6>
          <h6 class="blog_category_links"><a href="/blog_category_archive?category='Gynecomastia'">Gynecomastia</a></h6>
          <h6 class="blog_category_links"><a href="/blog_category_archive?category='Infographics'">Infographics</a></h6>
          <h6 class="blog_category_links"><a href="/blog_category_archive?category='Laser Lift'">Laser Lift</a></h6>
          <h6 class="blog_category_links"><a href="/blog_category_archive?category='Laser Liposuction'">Laser Liposuction</a></h6>
          <h6 class="blog_category_links"><a href="/blog_category_archive?category='Liposuction'">Liposuction</a></h6>
          <h6 class="blog_category_links"><a href="/blog_category_archive?category='Liposuction Surgery'">Male Breast Reduction</a></h6>
          <h6 class="blog_category_links"><a href="/blog_category_archive?category='Neck Liposuction'">Neck Liposuction</a></h6>
          <h6 class="blog_category_links"><a href="/blog_category_archive?category='Non-Invasive Procedures'">Non-Invasive Procedures</a></h6>
          <h6 class="blog_category_links"><a href="/blog_category_archive?category='Plastic Surgeons'">Plastic Surgeons</a></h6>
          <h6 class="blog_category_links"><a href="/blog_category_archive?category='Plastic Surgery'">Plastic Surgery</a></h6>
          <h6 class="blog_category_links"><a href="/blog_category_archive?category='SmartLipo'">SmartLipo</a></h6>
          <h6 class="blog_category_links"><a href="/blog_category_archive?category='SmartLipo Triplex'">SmartLipo Triplex</a></h6>
          <h6 class="blog_category_links"><a href="/blog_category_archive?category='Weight Loss'">Weight Loss</a></h6>
        </div>
      </div>
    </div>
  </div>
  <div class="container-fluid blog_index">
    <div class="row text-center">
      <h4 class="blog_index_heading">Archives</h4>
    </div>
    <div class="row text-center">
      <div class="col-xs-12">
        <h6 class="blog_months_links"><a href="/blog_month_archive?month_year='October 2015'">October 2015</a></h6>
        <h6 class="blog_months_links"><a href="/blog_month_archive?month_year='September 2015'">September 2015</a></h6>
        <h6 class="blog_months_links"><a href="/blog_month_archive?month_year='August 2015'">August 2015</a></h6>
        <h6 class="blog_months_links"><a href="/blog_month_archive?month_year='July 2015'">July 2015</a></h6>
        <h6 class="blog_months_links"><a href="/blog_month_archive?month_year='June 2015'">June 2015</a></h6>
        <h6 class="blog_months_links"><a href="/blog_month_archive?month_year='May 2015'">May 2015</a></h6>
        <h6 class="blog_months_links"><a href="/blog_month_archive?month_year='October 2014'">October 2014</a></h6>
        <h6 class="blog_months_links"><a href="/blog_month_archive?month_year='September 2014'">September 2014</a></h6>
        <h6 class="blog_months_links"><a href="/blog_month_archive?month_year='August 2014'">August 2014</a></h6>
        <h6 class="blog_months_links"><a href="/blog_month_archive?month_year='July 2014'">July 2014</a></h6>
        <h6 class="blog_months_links"><a href="/blog_month_archive?month_year='June 2014'">June 2014</a></h6>
        <h6 class="blog_months_links"><a href="/blog_month_archive?month_year='May 2014'">May 2014</a></h6>
      </div>
    </div>
  </div>
</div>
</div>  

Пользовательский фильтр xFutureDates

myApp.filter('xFutureDates', [function() {
    return function(array) {
        var results   = [],
            today     = new Date(),
            thisDay   = today.getDate(),
            thisMonth = (today.getMonth() + 1),
            thisYear  = today.getFullYear();

        angular.forEach(array, function(item, index) {
           if (item.month_id === thisMonth && item.year_id === thisYear && item.day_id > thisDay) {
            return null;
           } else {

            this.push(item);
           }
        }, results);

        return results;
    };
}]);

ОБНОВЛЕНИЕ с помощью Custom Filter recentMonths. Этот фильтр работает правильно в представлении и не отображает будущие даты. Вы можете найти код под заголовком "Последние блоги" в формате HTML/view.

myApp.filter('recentMonths', [function() {
    return function(array) {
        var results   = [],
            today     = new Date(),
            thisDay   = today.getDate(),
            thisMonth = (today.getMonth() + 1),
            lastMonth = today.getMonth(),
            thisYear  = today.getFullYear();

        angular.forEach(array, function(item, index) {
           if (item.month_id === thisMonth && item.year_id === thisYear && item.day_id <= thisDay) {
               this.push(item);
           } else if (item.month_id === lastMonth && item.year_id === thisYear ){
              this.push(item);
           }
        }, results);

        return results;
    };
}]);

JSON

[
  {
    "id": 51,
    "day_id": 26,
    "month_id": 11,
    "year_id": 2015,
    "month_year":"November 2015",
    "date": "November 26, 2015",
    "category": "Liposuction",
    "title": "Happy Thanksgiving from Timeless Esthetics",
    "description": "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum et Malorum\" (The Extremes of Good and Evil) by Cicero, written in 45 BC.\n\n  This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, \"Lorem ipsum dolor sit amet..\", comes from a line in section 1.10.32. The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from \"de Finibus Bonorum et Malorum\" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.\n\n Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum et Malorum\" (The Extremes of Good and Evil) by Cicero, written in 45 BC.\n\n This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, \"Lorem ipsum dolor sit amet..\", comes from a line in section 1.10.32. The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from \"de Finibus Bonorum et Malorum\" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham."
  },
  {
    "id": 50,
    "day_id": 12,
    "month_id": 10,
    "year_id": 2015,
    "month_year":"October 2015",
    "date": "October 12, 2015",
    "category": "Body Contouring, Liposuction, SmartLipo Triplex, Laser Lift",
    "title": "Smartlipo Triplex Liposuction Outcome Heavily Dependent on Plastic Surgeons Skill",
    "description": "Smartlipo Triplex laser liposuction is amongst the most requested body contouring procedures by both men and women. Unlike the conventional procedure, this minimally-invasive procedure uses safe and efficient laser technology to liquefy fat so that it can be easily removed. It also provides significant skin tightening effects. It is specifically designed to treat localized deposits of fat and its intelligent delivery systems help prevent overtreatment and minimize bleeding and bruising.\n\n Nevertheless, for optimal results, it is crucial that the plastic surgeon is trained and skilled in all of this body and facial/neck contouring technique. With the right surgeon, you can achieve a firmer and more aesthetically appealing result. Here are the main qualities to look for in your plastic surgeon if you are considering laser lipo treatment:\n\n The surgeon should have vast experience and skill in body contouring procedures and liposuction techniques. A skilled surgeon would have a thorough understanding of the skin, fascia, fat, muscle, bone, and cartilage of the face and body. Such knowledge is critical for effective contouring. The right surgeon will perform a detailed evaluation of the patients anatomical factors to develop a customized treatment plan to meet individual goals.\n\n The surgeon should also be compassionate and attentive to your concerns and be able to provide satisfactory answers to all your questions. The plastic surgeons primary concern should be your safety. The right physician will take all necessary measure to ensure safe procedures. Its important that feel comfortable discussing your concerns with the surgeon, so choose a physician with whom you are at ease. The right surgeon will provide you with all the relevant information about the treatment including the benefits as well as the risks, and guide you in taking an informed decision.\n\n Choosing a Cynosure certified AAAASF-accredited practice for your procedure would offer many benefits. The plastic surgeons in these facilities are experts in SmartLipo laser liposuction and train other surgeons in how to perform the procedure. They will provide the personal attention you deserve and help you achieve optimal results with an individualized treatment plan designed to address your specific concerns."
  }
]

Когда пользователь выполняет поиск в блоге, он возвращает/отображает все сообщения в блоге вместе со статьей "26 ноября 2015 года", которая является будущей датой.

Теги:

2 ответа

0
Лучший ответ

Выполнение следующих изменений внутри фильтра xFutureDates разрешило проблему:

myApp.filter('xFutureDates', [function() {
return function(array) {
    var results   = [],
        today     = new Date(),
        thisDay   = today.getDate(),
        thisMonth = (today.getMonth() + 1),
        thisYear  = today.getFullYear();

    angular.forEach(array, function(item, index) {
       if (item.month_id >= thisMonth && item.year_id === thisYear && item.day_id > thisDay) {
        return null;
       } else if(item.month_id > thisMonth && item.year_id >= thisYear){
        return null
       } else {

        this.push(item);
       }
    }, results);

    return results;
  };
}]);
0

Я думаю, что для использования нескольких фильтров вы должны написать свой ng-repeat, как это

ng-repeat="blog in blogs | filter: search_blogs | filter: xFutureDates | limitTo: 15" 

обратите внимание на filter: xFutureDates

  • 0
    Спасибо, я попробовал это, но это не сработало. Я не думал, что это была проблема, так как у меня есть другой фильтр recentMonths который работает правильно, но написан без filter: Это на самом деле прямо под заголовком «Недавние блоги» в представлении.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню