javascript - ng-repeat 解析 JSON 后无法显示

标签 javascript angularjs parsing angularjs-ng-repeat

有人能告诉我为什么 ng-repeat 对我不起作用吗? 如果 jsonFile 中出现 ng-repeat 问题,它会打印到表,但问题中的 ng-repeat 问题不会打印到表。 JSON 通常是从本地目录中提取的,但对于 codepen 添加了一个小的 JSON 作为变量。

注意:是的,将变量 $scope.jsonFile 更改为 $scope.problems 是有效的。那不是我的问题。我的问题是,一旦您解析用户输入并尝试将数据显示出来,它就不起作用。原始 json 和解析后的 json 上的 console.log() 看起来相同。这是我的问题。

检查源两个 $scope 都打印到控制台。

https://codepen.io/dneverson/pen/BvLyqW

main.js

let app = angular.module("MyApp", []);

app.controller("MyCtrl", function($scope, $http){

  // #################### GLOBALS ####################
  $scope.logTime = {};
  // #################### FUNCTIONS ##################

  //GET JSON FILE
  $http.get('./data/Problems2.json').then(function(response) {
    $scope.jsonFile =  response.data;
    console.log($scope.jsonFile);
  });
  // Shows or Hides button by Class ID
  $scope.displayButtons = function(classID){
    $(document).on('mouseenter', classID, function () {
      $(this).find(":button").show();
    }).on('mouseleave', classID, function () {
      $(this).find(":button").hide();
    });
  };
  // Hides an element by ID
  $scope.hideElement = function(elementID){
    document.getElementById(elementID).style.display = "none";
  };
  // Shows an element by ID
  $scope.showElement = function(elementID){
    document.getElementById(elementID).style.display = "block";
  };
  // Clears an element by ID
  $scope.clearElement = function(elementID){
    document.getElementById(elementID).innerHTML = "";
  };
  // Replaces element string by ID with given searchText
  $scope.addToElement = function(elementID, str){
    document.getElementById(elementID).innerHTML = str;
  };
  // Start time
  $scope.startTime = function(){
    $scope.logTime.start = Date.now();
  }
  // End time
  $scope.stopTime = function(){
    $scope.logTime.end = Date.now() - $scope.logTime.start;
    $scope.logTime.start = 0;
  }
  // Print timed results in console
  $scope.printTime = function(){
    if($scope.problems.length){
      console.log("Time: " + $scope.logTime.end +
                  "ms, Results: " + $scope.problems.length +
                  ", Records: " + $scope.jsonFile.length);
    };
  }
  //Add problem to Patients
  $scope.addProblem = function(data){
    var currDate = new Date();
    console.log(data);
    //_mel.melFunc('{MEL_ADD_PROBLEM("", ' + data.Description + ' , "", ' + currDate + ',"", "")}');
  };
  // Needed for searchJSON function
  $scope.addSlashes = function(str){
    return (str + '').replace(/[\\"'\(\)]/g, '\\$&').replace(/\u0000/g, '\\0');
  }
  // Searches JSON string for searchString
  $scope.searchJSON = function(searchStr){
    $scope.problems = [];
    return new Promise((resolve, reject) => {
      //console.log("jsonFile: " + typeof $scope.jsonFile + " content: " + $scope.jsonFile); //NOTE: [object Object],[object Object] WTF!!! on line 14 it is [{...},{...},{...},...]
      searchStr = $scope.addSlashes(searchStr).replace(' ', '[^"]+');
      let jsonStr = JSON.stringify($scope.jsonFile, null, ' '); //   , null, ' '
      let found = jsonStr.match(
        new RegExp('{\\s+"id":\\s"\\w+",\\s+"description":\\s.*'
        + searchStr + '.*",\\s+"weight":\\s[\\d\\.]+\\s+}','gi')
      );
      if (found){
        found.forEach((i) => {
        //  let tmp = JSON.stringify(i).replace(/\\n/g,'').replace(/\s\\/g,'').replace(/\\/g,'').replace(/"{\s/g,'{').replace(/\s}"/g,'}').replace(/,\s"/g,',"').replace(/:\s/g,':');
          $scope.problems.push(JSON.parse(i));
        });
      }
      resolve();
    });
  };

  // ################## CALL FUNCTIONS ################
  $scope.displayButtons(".tblRow");
  $scope.addToElement("error", "Type in the search bar for results.");
  document.getElementById("searchText").focus();
  $scope.showElement("searchTable");
  $("#searchText").on("paste keyup", function() { //"change paste keyup"

    if( $("#searchText").val().length >= 1){
      $scope.startTime();
      $scope.clearElement("error");
      $scope.showElement("searchTable");
      let searchText = $("#searchText").val().toLowerCase();
      $scope.searchJSON(searchText).then(console.log($scope.problems)); //Leaving promise in for future
      $scope.stopTime();
      $scope.printTime();
      if($scope.problems.length == 0){
        //$scope.hideElement("searchTable");
        $scope.addToElement("error", "No results containing all your search terms were found.");
      }
    }else{
      //$scope.hideElement("searchTable");
      $scope.addToElement("error", "Type in the search bar for results.");
    };
  });
});

index.html

<!DOCTYPE html>
<html lang="en" dir="ltr" ng-app="MyApp">
<head>
  <meta charset="utf-8">
  <title>HHS - Problems</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link rel="stylesheet" href="css/main.css">

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular-route.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

  <!--<script src="scripts/bundle.public.min.js" type="text/javascript"></script>-->
  <!--<script src="scripts/DemoController.js" type="text/javascript"></script>-->
  <script src="js/main.js"></script>
</head>

<body ng-controller="MyCtrl">
  <!-- Search Bar-->
  <div class="container well has-feedback search">
    <input type="text" class="form-control" id="searchText" placeholder="Search" autocomplete="off"/>
    <span class="glyphicon glyphicon-search form-control-feedback"></span>
  </div>

  <!-- Error Messages for User-->
  <div class="container">
    <div id="error"></div>
  </div>

  <!-- Search Results Table-->
  <div class="container well" id="searchTable" style="display:none;">
    <div class="row">
      <table class="table table-hover">
        <thead>
          <tr>
            <th>ID</th>
            <th>Description</th>
            <th>Weight</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          <tr class="tblRow" ng-repeat="problem in jsonFile | orderBy:'-Weight' track by $index" ng-class="{'color-grey': problem.Weight === 0, 'color-blue': problem.Weight <= 1 && problem.Weight > 0 , 'color-green': problem.Weight >= 1}">
            <td>{{problem.ID}}</td>
            <td>{{problem.Description}}</td>
            <td>{{problem.Weight}}</td>
            <td class="rowbtn"><button class="btn btn-success" ng-click="addProblem(problem)" style="display:none;">Add</button></td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>


</body>
</html>

main.css

h2{
  text-align: center;
}
#error{
  font-weight: bold;
  color: red;
}
.search{
  background-color: #00426c;
  margin-bottom: 0px;
  box-shadow: 0px 0px 50px #dadada;
}
.well{
  box-shadow: 0px 0px 50px #dadada;
}
.rowbtn{
  padding: 0 !important;
  width: 52px;
}
.form-control-feedback{
  top: 20px !important;
  right: 20px !important;
}
.glyphicon-search{
  color: #003152;
}

.color-red{
  color: red;
}
.color-blue{
  color: #31708f;
  background-color: #d9edf7;
  border-color: #bce8f1;
}
.color-green{
  color: #3c763d;
  background-color: #dff0d8;
  border-color: #d6e9c6;
}
.color-grey{
  color: #989898;
  background-color: #f1f1f1;
  border-color: #eaeaea;
}
.color-yellow{
  color: #8a6d3b;
  background-color: #fcf8e3;
  border-color: #faebcc;
}

Problems2.json

[
  {"ID": "A0103","Description": "Typhoid pneumonia","Weight": 0.205},
  {"ID": "A0104","Description": "Typhoid arthritis","Weight": 0.51},
  {"ID": "A0105","Description": "Typhoid osteomyelitis","Weight": 0.51},
  {"ID": "A021","Description": "Salmonella sepsis","Weight": 0.548},
  {"ID": "A0222","Description": "Salmonella pneumonia","Weight": 0.205},
  {"ID": "A0223","Description": "Salmonella arthritis","Weight": 0.51},
  {"ID": "A0224","Description": "Salmonella osteomyelitis","Weight": 0.51},
  {"ID": "A065","Description": "Amebic lung abscess","Weight": 0.205},
  {"ID": "A072","Description": "Cryptosporidiosis","Weight": 0.451},
  {"ID": "A202","Description": "Pneumonic plague","Weight": 0.205},
  {"ID": "A207","Description": "Septicemic plague","Weight": 0.548},
  {"ID": "A212","Description": "Pulmonary tularemia","Weight": 0.205},
  {"ID": "A221","Description": "Pulmonary anthrax","Weight": 0.205},
  {"ID": "A227","Description": "Anthrax sepsis","Weight": 0.548},
  {"ID": "A267","Description": "Erysipelothrix sepsis","Weight": 0.548},
  {"ID": "A310","Description": "Pulmonary mycobacterial infection","Weight": 0.451},
  {"ID": "A312","Description": "Disseminated mycobacterium avium-intracellulare complex (DMAC)","Weight": 0.451},
  {"ID": "A327","Description": "Listerial sepsis","Weight": 0.548},
  {"ID": "A3681","Description": "Diphtheritic cardiomyopathy","Weight": 0.377},
  {"ID": "A3684","Description": "Diphtheritic tubulo-interstitial nephropathy","Weight": 0},
  {"ID": "A391","Description": "Waterhouse-Friderichsen syndrome","Weight": 0.251},
  {"ID": "A392","Description": "Acute meningococcemia","Weight": 0.548},
  {"ID": "A393","Description": "Chronic meningococcemia","Weight": 0.548},
  {"ID": "A394","Description": "Meningococcemia, unspecified","Weight": 0.548},
  {"ID": "A3983","Description": "Meningococcal arthritis","Weight": 0.51},
  {"ID": "A3984","Description": "Postmeningococcal arthritis","Weight": 0.51},
  {"ID": "A400","Description": "Sepsis due to streptococcus, group A","Weight": 0.548},
  {"ID": "A401","Description": "Sepsis due to streptococcus, group B","Weight": 0.548},
  {"ID": "A403","Description": "Sepsis due to Streptococcus pneumoniae","Weight": 0.548},
  {"ID": "A408","Description": "Other streptococcal sepsis","Weight": 0.548},
  {"ID": "A409","Description": "Streptococcal sepsis, unspecified","Weight": 0.548},
  {"ID": "A4101","Description": "Sepsis due to Methicillin susceptible Staphylococcus aureus","Weight": 0.548},
  {"ID": "A4102","Description": "Sepsis due to Methicillin resistant Staphylococcus aureus","Weight": 0.548},
  {"ID": "A411","Description": "Sepsis due to other specified staphylococcus","Weight": 0.548},
  {"ID": "A412","Description": "Sepsis due to unspecified staphylococcus","Weight": 0.548},
  {"ID": "A413","Description": "Sepsis due to Hemophilus influenzae","Weight": 0.548},
  {"ID": "A414","Description": "Sepsis due to anaerobes","Weight": 0.548},
  {"ID": "A4150","Description": "Gram-negative sepsis, unspecified","Weight": 0.548},
  {"ID": "A4151","Description": "Sepsis due to Escherichia coli [E. coli]","Weight": 0.548},
  {"ID": "A4152","Description": "Sepsis due to Pseudomonas","Weight": 0.548},
  {"ID": "A4153","Description": "Sepsis due to Serratia","Weight": 0.548},
  {"ID": "A4159","Description": "Other Gram-negative sepsis","Weight": 0.548},
  {"ID": "A4181","Description": "Sepsis due to Enterococcus","Weight": 0.548},
  {"ID": "A4189","Description": "Other specified sepsis","Weight": 0.548},
  {"ID": "A419","Description": "Sepsis, unspecified organism","Weight": 0.548},
  {"ID": "A420","Description": "Pulmonary actinomycosis","Weight": 0.205},
  {"ID": "A427","Description": "Actinomycotic sepsis","Weight": 0.548},
  {"ID": "A430","Description": "Pulmonary nocardiosis","Weight": 0.205},
  {"ID": "A480","Description": "Gas gangrene","Weight": 1.449},
  {"ID": "A481","Description": "Legionnaires' disease","Weight": 0.689},
  {"ID": "A483","Description": "Toxic shock syndrome","Weight": 0.548},
  {"ID": "A5055","Description": "Late congenital syphilitic arthropathy","Weight": 0.51},
  {"ID": "A5204","Description": "Syphilitic cerebral arteritis","Weight": 0},
  {"ID": "A5440","Description": "Gonococcal infection of musculoskeletal system, unspecified","Weight": 0.51},
  {"ID": "A5441","Description": "Gonococcal spondylopathy","Weight": 0.51},
  {"ID": "A5442","Description": "Gonococcal arthritis","Weight": 0.51},
  {"ID": "A5443","Description": "Gonococcal osteomyelitis","Weight": 0.51},
  {"ID": "A5449","Description": "Gonococcal infection of other musculoskeletal tissue","Weight": 0.51},
  {"ID": "A5484","Description": "Gonococcal pneumonia","Weight": 0.205},
  {"ID": "A5485","Description": "Gonococcal peritonitis","Weight": 0.318},
  {"ID": "A5486","Description": "Gonococcal sepsis","Weight": 0.548},
  {"ID": "A666","Description": "Bone and joint lesions of yaws","Weight": 0.51},
  {"ID": "A6923","Description": "Arthritis due to Lyme disease","Weight": 0.51},
  {"ID": "A8100","Description": "Creutzfeldt-Jakob disease, unspecified","Weight": 0},
  {"ID": "A8101","Description": "Variant Creutzfeldt-Jakob disease","Weight": 0},
  {"ID": "A8109","Description": "Other Creutzfeldt-Jakob disease","Weight": 0},
  {"ID": "A811","Description": "Subacute sclerosing panencephalitis","Weight": 0},
  {"ID": "A812","Description": "Progressive multifocal leukoencephalopathy","Weight": 0},
  {"ID": "A8181","Description": "Kuru","Weight": 0},
  {"ID": "A8182","Description": "Gerstmann-Straussler-Scheinker syndrome","Weight": 0},
  {"ID": "A8183","Description": "Fatal familial insomnia","Weight": 0},
  {"ID": "A8189","Description": "Other atypical virus infections of central nervous system","Weight": 0},
  {"ID": "A819","Description": "Atypical virus infection of central nervous system, unspecified","Weight": 0},
  {"ID": "A985","Description": "Hemorrhagic fever with renal syndrome","Weight": 0},
  {"ID": "B007","Description": "Disseminated herpesviral disease","Weight": 0.548},
  {"ID": "B0082","Description": "Herpes simplex myelitis","Weight": 0.522},
  {"ID": "B0112","Description": "Varicella myelitis","Weight": 0.522},
  {"ID": "B0221","Description": "Postherpetic geniculate ganglionitis","Weight": 0},
  {"ID": "B0222","Description": "Postherpetic trigeminal neuralgia","Weight": 0},
  {"ID": "B0223","Description": "Postherpetic polyneuropathy","Weight": 0},
  {"ID": "B0224","Description": "Postherpetic myelitis","Weight": 0.522},
  {"ID": "B0229","Description": "Other postherpetic nervous system involvement","Weight": 0},
  {"ID": "B0682","Description": "Rubella arthritis","Weight": 0.51},
  {"ID": "B180","Description": "Chronic viral hepatitis B with delta-agent","Weight": 0.257},
  {"ID": "B181","Description": "Chronic viral hepatitis B without delta-agent","Weight": 0.257},
  {"ID": "B182","Description": "Chronic viral hepatitis C","Weight": 0.257},
  {"ID": "B188","Description": "Other chronic viral hepatitis","Weight": 0.257},
  {"ID": "B189","Description": "Chronic viral hepatitis, unspecified","Weight": 0.257},
  {"ID": "B20","Description": "Human immunodeficiency virus [HIV] disease","Weight": 0.482},
  {"ID": "B250","Description": "Cytomegaloviral pneumonitis","Weight": 0.451},
  {"ID": "B251","Description": "Cytomegaloviral hepatitis","Weight": 0.451},
  {"ID": "B252","Description": "Cytomegaloviral pancreatitis","Weight": 0.451},
  {"ID": "B258","Description": "Other cytomegaloviral diseases","Weight": 0.451},
  {"ID": "B259","Description": "Cytomegaloviral disease, unspecified","Weight": 0.451},
  {"ID": "B2685","Description": "Mumps arthritis","Weight": 0.51},
  {"ID": "B3324","Description": "Viral cardiomyopathy","Weight": 0.377},
  {"ID": "B371","Description": "Pulmonary candidiasis","Weight": 0.451},
  {"ID": "B377","Description": "Candidal sepsis","Weight": 0.548},
  {"ID": "B377","Description": "Candidal sepsis","Weight": 0.451},
  {"ID": "B3781","Description": "Candidal esophagitis","Weight": 0.451},
  {"ID": "B380","Description": "Acute pulmonary coccidioidomycosis","Weight": 0.205},
  {"ID": "B381","Description": "Chronic pulmonary coccidioidomycosis","Weight": 0.205},
  {"ID": "B382","Description": "Pulmonary coccidioidomycosis, unspecified","Weight": 0.205},
  {"ID": "B390","Description": "Acute pulmonary histoplasmosis capsulati","Weight": 0.205},
  {"ID": "B391","Description": "Chronic pulmonary histoplasmosis capsulati","Weight": 0.205},
  {"ID": "B392","Description": "Pulmonary histoplasmosis capsulati, unspecified","Weight": 0.205},
  {"ID": "B400","Description": "Acute pulmonary blastomycosis","Weight": 0.205},
  {"ID": "B401","Description": "Chronic pulmonary blastomycosis","Weight": 0.205},
  {"ID": "B402","Description": "Pulmonary blastomycosis, unspecified","Weight": 0.205},
  {"ID": "B410","Description": "Pulmonary paracoccidioidomycosis","Weight": 0.205},
  {"ID": "B4282","Description": "Sporotrichosis arthritis","Weight": 0.51},
  {"ID": "B440","Description": "Invasive pulmonary aspergillosis","Weight": 0.451},
  {"ID": "B441","Description": "Other pulmonary aspergillosis","Weight": 0.451},
  {"ID": "B442","Description": "Tonsillar aspergillosis","Weight": 0.451},
  {"ID": "B447","Description": "Disseminated aspergillosis","Weight": 0.451},
  {"ID": "B4481","Description": "Allergic bronchopulmonary aspergillosis","Weight": 0.281},
  {"ID": "B4489","Description": "Other forms of aspergillosis","Weight": 0.451},
  {"ID": "B449","Description": "Aspergillosis, unspecified","Weight": 0.451},
  {"ID": "B450","Description": "Pulmonary cryptococcosis","Weight": 0.451},
  {"ID": "C6300","Description": "Malignant neoplasm of unspecified epididymis","Weight": 0.158}
]

最佳答案

我不得不说这是一种奇怪的方法,但问题是你正在加载 $scope.problems在 Angular 的消化周期之外。因此,Angular 不知道通知 View 进行更新,因此您永远看不到搜索结果,即使您可以 console.log($scope.problems)并看到它确实有一个值的集合。要解决此问题而不更改您创建的结构,您需要包装将值推送到 $scope.problems 的代码部分。在 $scope.$apply()堵塞。在您的$scope.searchJSON()内函数进行此修改以通知 Angular 您已修改 $scope.problems集合,然后搜索结果将显示在您的 View 中:

if (found) {
    $scope.$apply(() => {
        found.forEach((i) => {
        //  let tmp = JSON.stringify(i).replace(/\\n/g,'').replace(/\s\\/g,'').replace(/\\/g,'').replace(/"{\s/g,'{').replace(/\s}"/g,'}').replace(/,\s"/g,',"').replace(/:\s/g,':');
          $scope.problems.push(JSON.parse(i));
        });
    });
  }

关于javascript - ng-repeat 解析 JSON 后无法显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53822556/

相关文章:

javascript - 知道网站的来源吗?

javascript - 最新的 jquery ui 不再支持按年份选择的日期选择器?

javascript - 通过Ajax调整图片大小并上传

javascript - 使用 IE11 的文本区域和占位符属性的 AngularJS v1.2.5 脚本错误

angularjs - angular-google-maps 中心缩放多个标记

parsing - 解决 LALR 歧义

c - 从字符串 C 中获取 int 值

javascript - 窗口旋转或切换不同设备的javascript事件是什么?

c# - 如何从 Webapi 将 URL 传递到 <img> 标记以接受 base64 图像?

java - Jsoup.connect().get() 仅获取 Android 上的部分 html 文件