Ivan Chepurin Ivan Chepurin - 1 year ago 68
Javascript Question

option selected not working from AngularJS template

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.


<td colspan="2" align="right">
Sort headers by:
<select ng-model="sortHeaders">
<option value="rating">Rating</option>
<option value="id" selected>ID</option>
<tr ng-repeat="header in headers | filter:search | orderBy:sortHeaders">

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

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:


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 Source
 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>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download