0

I need to list the all objects in the select element and the first object must be selected by default.

This is the controller to get all objects:

$scope.categories = function() {
    $http(
            {
                method : 'GET',
                url : '/prodemo/categories'
            }).success(
                    function(data, status, headers, config) {
                        $scope.categories = data;
            }).error(
                    function(data, status, headers, config) {
            });
};

And this is the select element:

<div data-ng-init="categories()">
    <select ng-model="category" ng-options="category.name for category in categories"> </select>
</div>
2
  • What does the data look like? Commented Jul 8, 2015 at 13:45
  • @Chrillewoodz Hi, there is no problem with the list, my problem is when I want to set the first object in the select element. I need the select element get the first object by default. Commented Jul 8, 2015 at 13:58

2 Answers 2

2

Put this line in your controller:

$scope.category = categories[0];

It will initialize the first category option as the default one.

Sign up to request clarification or add additional context in comments.

Comments

0

Firstly I would recommend you to use services instead of making $http calls in controller(s), to make modular, reusable and more testable code. (And what not advantages) Then, perhaps, you should take a look at controllerAs instead of using $scope.

Setting the default option can be achieved by using the first element of your array as the value of your model.

Here is a plunker (without controllerAs) that uses a service and resolves the data when done.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.