簡體   English   中英

ng-repeat中的div無法更新?

[英]div in ng-repeat is not getting updated?

我從http get請求中獲得響應,而Iam使用響應來迭代數據

<div id="container" ng-app="myApp" ng-controller="myctrl">
     <div ng-repeat="profile in profiles">
          <p>{{profile.username}}</p>
     </div>
</div>

這是用於在點擊時添加一個配置文件

<input ng-click="addProfile()" type="button" value="add Profile" />

這是我在控制器中的獲取請求

var app = angular.module('myApp', []);
app.controller('myctrl', function($scope, $http) {
 $scope.profiles = [];
 $http.get("test1.json")
 .then(function(response) {
     $scope.profiles = response.data.profiles; //Response is provided below
 });
$scope.addProfile = function(){
      $http.get('test2.json')
     .then(function(response) {
       alert("af");
         $scope.items = response.data.profiles; //Response is provided below
         $scope.profiles.push($scope.items);
         console.log($scope.profiles); //gives the update Array

            });
        });
});

我對test1.json的獲取請求的響應

{
   "Id": "44442232",
    "profiles": [
        {
           "type": "Friend",
           "username": "Username 1",
         },
         {
            "type": "Student ",
            "username": "Username 2",
           }
       ]
   } 

我對test2.json的獲取請求的響應

{
   "Id": "44442232",
    "profiles": [
        {
           "type": "Friend",
           "username": "Username 4",
         },
         {
            "type": "Student ",
            "username": "Username 5"
           }
       ]
   } 

我在數組中更新后嘗試了console.log已更新但ng-repeat的div沒有更新?

請在末尾加上“)”,以關閉JSON調用請求。 除此之外沒有任何錯誤,相同的代碼對我來說很好。 //代碼在這里

var myApp = angular.module("myApp", []);
myApp.controller("myctrl", function($scope, $http) {

$http.get('test1.json')
 .then(function(response) {
   $scope.profiles = response.data.profiles; //Response is provided below
 });

   $scope.addProfile = function(){
     $http.get('test2.json')
     .then(function(response) {
         $scope.items = response.data.profiles; //Response is provided below
         angular.forEach($scope.items, function(value) {
           $scope.profiles.push(value);
         });
         console.log($scope.profiles);

     });

 };

});

請找到此更新的js代碼並檢查。 一旦修復,請通知我。 快樂的編碼:)

首先,我認為您不需要$ scope。$ apply()來觸發摘要循環。 您處在有角度的環境中。

其次,您在調用.then()時缺少一個')'。 您目前擁有'.then(function(){};'

第三,如果響應屬性是對象中的最后一個,則該響應對象的username名稱后面不應包含逗號。

另外,您是否有無提示的失敗,或者是控制台中的錯誤,並且ng-repeat的已處理html為空白,還是獲得了角插值語法{{profile.username}}?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM