2017-05-25 62 views
0

嗨我正在angularjs中開發web應用程序。我正在嘗試將數據綁定到drodpown。我正在調用ajax來從服務器獲取數據。我收到錯誤無法讀取未定義的屬性「長度」。我正在取得請求。這是我的api。 http://192.168.0.213:1234/api/Customer/Nationalities如何將數組數據綁定到angularjs的下拉列表中?

以上API將

{"status":"Success","msg":"Success","code":"200","data":[{"ID":1,"Nationality":"indian"},{"ID":2,"Nationality":"england"}]} 

我使用JS綁定如下返回。

var url = cfg.Baseurl; 
      var nationality = new Array(); 
      $http.get(url + 'api' + '/Customer/' + 'Nationalities').success(function (data) { 
       $.map(data.data.Nationality, function (item) { 
        nationality.push(item); 
        console.log(item); 
       }); 
       $scope.nationalityList = nationality; 
      }).error(function (status) { 
      }); 

這是我的HTML代碼。

<select ng-model="user.nationality" id="brand" ng-options="user.nationality for user in nationalityList" required> 
          <option value="" label="Select">Select</option> 
         </select> 

我結束了無法讀取未定義錯誤的屬性「長度」。任何幫助,將不勝感激。謝謝。

+2

在你的控制器,你可以試試你的初始化數組到一個空數組.. ..'$ scope.nationalityList = []' – mridula

回答

1

這裏是演示鏈接Jsfiddle demo

JS代碼

var app = angular.module('myApp', []); 

    app.controller('ctrl', function($scope) { 
    $scope.nationalityList = { 
     "status": "Success", 
     "msg": "Success", 
     "code": "200", 
     "data": [{ 
     "ID": 1, 
     "Nationality": "indian" 
     }, { 
     "ID": 2, 
     "Nationality": "england" 
     }] 
    }; 
    }); 

** ** HTML

<div ng-app='myApp'> 

    <div ng-controller='ctrl'> 
     <select ng-model="user.nationality" id="brand" ng-options="user.Nationality for user in nationalityList.data" required> 
     <option value="" label="Select">Select</option> 
     </select> 
     <span>nationality = {{user.nationality}}</span> 
    </div> 
    </div> 

希望這將幫助你

1

在這種情況下,它沒有必要映射,它只分配th該陣列

var url = cfg.Baseurl; 
var nationality = []; 
$http.get(url + 'api' + '/Customer/' + 'Nationalities') 
.success(function (data) { 
    if(data.data) { 
     // Here the value is assigned 
     $scope.nationalityList = data.data; 
    } 
}).error(function (status) { }); 

電子價值和你的HTML必須是這樣的

<select 
    ng-model="selectedNationality" 
    id="brand" 
    ng-options="item.Nationality for item in nationalityList" 
    required> 
    <option value="" label="Select">Select</option> 
</select> 
<!-- Showing selected option --> 
<p ng-if="selectedNationality">Selected option: {{selectedNationality}}<p/> 

欲瞭解更多信息https://docs.angularjs.org/api/ng/directive/ngOptions

1

因爲$scope.nationalityList沒有初始化,它在時間當視圖未定義正在呈現。因此錯誤Cannot read property 'length' of undefined error.

只要初始化變量爲空數組將解決這一錯誤。

0
$.map(data.data.Nationality, function (item) { 
        nationality.push(item); 
        console.log(item); 
       }); 

data.data.Nationality是無效的,因爲data.data是一個數組,而不是反對 那麼,國籍= data.data 將做工精細

相關問題