2016-01-04 25 views
0

我有一個頁面,我們可以從後臺獲取使用角度$ http的用戶列表,如下所示。ng-repeat後無法使用AngularJS代碼

myApp.controller("MyCntrl", function ($scope, $http) { 
    $scope.users= []; 
    $scope.countries = function() { 
     $http.get(url).success(function (data, status, headers, config) { 
      return data; 
     }); 
    }; 

    $scope.getUsers = function() { 
     $http.get(url).success(function (data, status, headers, config) { 
      $scope.users= data; 
     }); 
    }; 
}); 

而我的HTML是這樣的:

<div ng-app="myApp" ng-controller="MyCntrl" ng-init="getUsers()"> 
    <p ng-repeat="user in users">{{user.UserName}}</p> 

    <select> 
     <option ng-repeat="country in countries">{{country.CountryName}}</option> 
    </select> 
</div> 

一切正常最多顯示的用戶。

但用戶的ng-repeat後的代碼不起作用。我無法看到下拉列表中的國家/地區列表。 我可以看到螢火蟲用戶和國家的json列表。 任何人都可以幫助我嗎?

我的國家JSON是

[{CountryId:1,CountryName:"India"}] 

我所觀察到的是,角碼是不是用戶的第一NG重複工作後。 當我嘗試看看長的國家JSON像

<p>{{countries.length}}</p> 

它僅僅是打印{{countries.length}}在瀏覽器

+0

'收益率=數據呼叫功能;'?爲您的國家設置範圍變量,如您所做的那樣_users_ – Rayon

+0

發佈您的國家json – Sajeetharan

+0

@RayonDabre對不起其錯字。其返回數據; – Aravind

回答

0

你將不得不使用ng-options中,而不是<select>情況:

<select ng-model="selectedCountry" ng-options="country.countryName for country in countriesData"> 
</select> 

編輯

替換此:

$scope.countries = function() { 
    $http.get(url).success(function (data, status, headers, config) { 
    return data; 
    }); 
}; 

通過這樣的:

$http.get(url).success(function (data, status, headers, config) { 
    $scope.countriesData = data; 
}); 

注:經檢查發現url定義!

+0

不能使用ng-options。同樣''裏面'返回'成功沒有什麼 – charlietfl

+0

謝謝。更新我的回答 –

+0

成功內部的「return」是我指出要替換的代碼。 –

0

您可以設置,就像你爲$scope.users做了$scope.countries返回的數據,除非你不需要定義你最好在你看來調用來獲取所有國家的功能。

相反,請致電您的控制器此功能這反過來將countries變量設置成範圍:

this.getCountries = function() { 
    $http.get(url).success(function (data, status, headers, config) { 
     $scope.countries = data; 
    }); 
}; 

// call the method to get the countries 
this.getCountries(); 

注意,在你的代碼中有return = data這可能會導致一個語法錯誤。

0

你有NG-重複,這就是爲什麼它不工作properly.Correct代碼應該是像下面

myApp.controller("MyCntrl", function ($scope, $http) { 
    $scope.users= []; 
    $scope.getCountry = function() { 
     $http.get(url).success(function (data, status, headers, config) { 
      $scope.countries = data; 
     }); 
    }; 

    $scope.getUsers = function() { 
     $http.get(url).success(function (data, status, headers, config) { 
      $scope.users= data; 
      $scope.getCountry(); 
     }); 
    }; 
});