option selected not working from AngularJS template

Ivan Chepurin picture Ivan Chepurin · Jul 14, 2015 · Viewed 14.5k times · Source

I'm new to AngularJS, so it could be really simple, but I just can't seem to figure it out. The problem is not in the AngularJS code itself, but I'm sure it is somehow connected, because I've tried it in a blank pure-HTML test page, and it worked, how it's supposed to.

headers.html:

<table>
<thead>
    <tr>
        <td colspan="2" align="right">
            Sort headers by:
            <select ng-model="sortHeaders">
                <option value="rating">Rating</option>
                <option value="id" selected>ID</option>
            </select>
        </td>
    </tr>
    <tr>
        <th>Rating</th>
        <th>Header</th>
    </tr>
</thead>
<tbody>
    <tr ng-repeat="header in headers | filter:search | orderBy:sortHeaders">
        <td>{{header.rating}}</td>
        <td>{{header.title}}</td>
    </tr>
</tbody>

The problem here is, as the title says, with <option value="id" selected> not being selected at page load, how it's supposed to be. headers.html is, obviously, a template for data output. And it does the job perfectly, except for this selected problem.

It's loaded from headers_app.js:

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

headersApp.directive('headers', [function () {
return {
    restrict: 'E',
    controller: function($scope, $http) {
        $http.get('/api/headers.json').success(function(data) {
            $scope.headers = data.headers;
        });
    },
    templateUrl: '/templates/headers.html',
    replace: true,
    link: function (scope, element, attrs) {
        console.log('linked headersApp');
    }
};
}]);

and, of course, there is this guy inside index.html:

...
<headers>
</headers>
...

Once again, everything else works as expected. The only problem is that supposed-to-be-selected option is not actually selected at page load.

Any ideas?

Answer

gr3g picture gr3g · Jul 14, 2015
 link: function (scope, element, attrs) {
       scope.sortHeaders  = "id";
    }

As said in other responses, you can do it this way also:

<select ng-model="sortHeaders">
    <option value="rating">Rating</option>
    <option value="id" ng-selected="true">ID</option>
</select>