Reputation: 668
I have JSON being returned that looks like this
[{"Phone_Type_Code":1,"Phone_Type_Desc":"Cell","Valid_Date":"2014-01-01T00:00:00.000Z","Expiration_Date":null},{"Phone_Type_Code":2,"Phone_Type_Desc":"Home","Valid_Date":"2014-01-01T00:00:00.000Z","Expiration_Date":null},{"Phone_Type_Code":3,"Phone_Type_Desc":"Office","Valid_Date":"2014-01-01T00:00:00.000Z","Expiration_Date":null},{"Phone_Type_Code":4,"Phone_Type_Desc":"Other","Valid_Date":"2014-01-01T00:00:00.000Z","Expiration_Date":null}]
I have a scope in my controller that looks like this:
$scope.phoneTypes = function(){
return $http.get("/api/lookup/Phone_Type").then(function(response){
return response.data;
});
};
Then a select that looks like :
<select ng-model="phoneTypes" ng-options="value.Phone_Type_Code as value.Phone_Type_Desc for (key,value) in phoneTypes">
<option value="">Select One</option>
</select>
But when I run it the break point does not even hit inside the phoneTypes method and nothing is populated. What am I doing wrong?
Upvotes: 0
Views: 675
Reputation: 559
Name your ng-model as "selectedPhoneType".
Your data is an array and not an object, as such, use the "x.Code as x.Desc for x in phoneTypes" syntax.
Use "track by" to populate the values if you want, see https://stackoverflow.com/a/22997081/4022015. But note that, in the controller, even without the "track by" statement, $scope.selectedPhoneType shall still contain the correct "Code" value. Don't worry about the generated html.
Upvotes: 0
Reputation: 40863
$scope.phoneTypes
is a function so if you want to use it inside of the ngOptions
you need to call it as such ... in phoneTypes()
However with that being said you might run into a problem when the digest cycle checks and you end up making another call to your api.
If you assign it to the scope it won't make another call to the api during the digest cycle.
$scope.phoneTypes = [];
$http.get("/api/lookup/Phone_Type").then(function(response){
$scope.phoneTypes = response.data;
});
Example on jsfiddle that uses $timeout()
to simulate a delay
Upvotes: 4