Rob
Rob

Reputation: 738

Dynamically set select options using AngularJS

I'm trying to dynamically set the options of a select list and am stuck on what I need to put in the ng-options parameter to make it work as I want it to.

Here is the JSON

{ 
   "131":"Activity A",
   "141":"Activity B",
   "143":"Activity C",
   "186":"Activity D",
   "187":"Activity E",
}

My select list is...

 <select size="7" ng-model="selectedItems" ng-options="item.id as item.name for item in rlist">

My app.js is...

    angular.module('qAssign', []).controller('qCtrl', function ($scope, $http) {
        $scope.selectedItems = null;
        $scope.rlist = [];

        $http({
            method: 'GET',
            url: 'pathtoJSON.php',
            data: { applicationId: 1 }
        }).success(function (result) {
            $scope.rlist = result;
        });

    });

What gets rendered is

<option value="">undefined</option>
<option value="">undefined</option>
<option value="">undefined</option>
<option value="">undefined</option>
<option value="">undefined</option>

But what I'd like is

<option value="131">Activity A</option>
<option value="141">Activity B</option>
<option value="143">Activity C</option>
<option value="186">Activity D</option>
<option value="187">Activity E</option>

I know my ng-options is incorrect, I just don't know what it should be.

Thanks.

Upvotes: 0

Views: 1420

Answers (4)

Coder John
Coder John

Reputation: 786

Yes sure you can do this on your server side:

$arr_temp = array (131 => Activity A, 132 => Activity B);
$arr_json = array();

foreach ($arr_temp as $key => $val) {
 $arr_json[] = array('id' => $key, 'name' => $val);
}  

return json_encode($arr_json);

Upvotes: 0

ssuperczynski
ssuperczynski

Reputation: 3426

Try to use angular.copy

$http.get('pathtoJSON.php', {applicationId: 1})
    .success(function (result) {
        angular.copy(result, $scope.rlist);
    });

Upvotes: 0

Coder John
Coder John

Reputation: 786

It should array of objects

     [
      { id:"131", name:"Activity A"},
      { id:"132", name:"Activity B"},
      { id:"133", name:"Activity A"}
     ]

Upvotes: 0

ngLover
ngLover

Reputation: 4588

You are taking options in wrong way .take it as .

 angular.module('qAssign', []).controller('qCtrl', function ($scope, $http) {
        $scope.selectedItems = null;
        $scope.rlist = [];

        $http({
            method: 'GET',
            url: 'pathtoJSON.php',
            data: { applicationId: 1 }
        }).success(function (result) {
            $scope.rlist = result;
             $scope.selectedItems = result.131;
        });

    });

Upvotes: 1

Related Questions