在ng-repeat中写条件

时间:2017-01-11 12:14:40

标签: angularjs

我刚刚开始学习Angular JS并且我正在准备一个测试库系统并且在ng-repeat中遇到了一个小问题

我有2张桌子。一个存储有关书籍的详细信息,另一个是借用该书的学生。

表1- book_id, book_name, borrowed, student_id

表2 - book_id, student_ name, student_id

有两个单独的函数可以从上面的每个表中获取所有细节。

下面的代码显示了从第一张表中抓取的所有书籍

<div class=”available” ng-repeat="book in books">{{book.book_name}}</div>

我想做的是

If  borrowed == 1

更改班级=&#34; not_available&#34;并在div中添加student_name和book_name,需要从具有学生详细信息的学生那里抓取。

JS代码

 function studentsController($scope,$http) {
     $scope.students = [];
     $http.get('<?php echo site_url('angularjs/get_students'); ?>').success(function($data){ $scope.students=$data; });
 }

  function booksController($scope,$http) {
     $scope.books = [];
     $http.get('<?php echo site_url('angularjs/get_books'); ?>').success(function($data){ $scope.books=$data; });
 }

我确实尝试了filterng-if,但我无法实现上述目标

任何帮助将不胜感激

3 个答案:

答案 0 :(得分:1)

如果你有两个阵列

  • 第一个是booksbook_id, book_name, borrowed, student_id
  • 第二个是studentsbook_id, student_ name, student_id

然后转到以下方式来实现您的概念(只需将其作为关键

<div class="available" ng-repeat="book in books">
    {{book.book_name}}
    <div ng-repeat="student in students ">
        <div class="not_available"  ng-show="student.book_id==book.book_id>
          {{book.book_name}} is already purchased by {{student.student_ name}}
        </div>
   </div>
</div>

答案 1 :(得分:1)

我会把它全部放在一个控制器中,以避免引用另一个控制器。

function libraryController($scope,$http) {
  $scope.students = [];
  $http.get('<?php echo site_url('angularjs/get_students'); ?>').success(function($data){ $scope.students=$data; });

  $scope.books = [];
  $http.get('<?php echo site_url('angularjs/get_books'); ?>').success(function($data){ $scope.books=$data; });

  $scope.getBookBorrowerName = function(book){
    for (var s=0; s<$scope.students.length; s++){
      if (book.student_id == $scope.students[s].student_id){
        return ' - Borrowed by: ' + $scope.students[s].student_name;
      }
    }
  };
}

然后你的html会是这样的:

<div ng-repeat="book in books" ng-class="book.borrowed != 1 ? 'available' : 'not_available'">{{book.book_name + book.borrowed == 1 ? getBookBorrowerName(book) : ''}}</div>

答案 2 :(得分:0)

希望这会对你有所帮助

angular.module('moduleName')
.controller('ctrName', [function($scope) {
   $scope.books = [......];
   $scope.students = [......];

   $scope.getStuDetailsByBookId = function(book_id, prop) {
     // some login to get student object from students collection
     return studenDetails[prop];
   };
}]);


<div ng-controller="nameController">
   <div ng-repeat="book in books" ng-class="{'not-avail': book.borrowed == 1, 'other' : book.borrowed != 1}">
     <div ng-if="book.borrowed == 1">
      {{getStuDetailsByBookId(book.book_id, 'name')}}
      {{getStuDetailsByBookId(book.book_id, 'id')}}
     </div>
   </div>

</div>