2015-08-21 37 views
0

我需要從控制器中填充模板html文件中的選擇(選項)元素。我能做到這一點成功,但不能放棄默認值(以避免第一空選項)來自控制器的templateUrl中的訪問元素 - AngularJS

template.html文件

... 
<select name="drill_down" id="drill_down" ng-model="drill_down" 
ng-options="item.value for item in items"></select> 
... 

controller.js文件

(function() { 
    'use strict'; 

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

app.config(function($stateProvider) { 
    $stateProvider 
     .state('appname', { 
      url: '/appname', 
      templateUrl: '/appname/template.html', 
      controller: 'AppCtrl' 
     }); 
}); 

app.controller('AppCtrl', AppCtrl); 

function AppCtrl($scope, MyService) { 
    $scope.college_majors_full = []; 
    $scope.job_title_functions = []; 

    MyService.getData().then(function(rows) { 
     $scope.items = rows; // this works - populates select options 

     $scope.drill_down = $scope.items[0].value; // this doesn't work 
    }); 
... 

任何幫助嗎?謝謝。

回答

1

您的選擇有

您正在分配值,而不是ID

嘗試這樣

$scope.drill_down = $scope.items[0].value; 

或者你可以在期權創造價值的文本類型的項目只有文本屬性

請試試這個

查看

<select name="drill_down" id="drill_down" ng-model="drill_down" 
ng-options="item.id as item.value for item in items"></select> 

控制器

$scope.drill_down = $scope.items[0].id; 
+0

感謝您的幫助!有用。但現在它選擇最後一個選項作爲默認值。 即使我選擇另一個選項,總是隻選擇最後一個選項。 – Alex

+0

你能提供一個小提琴嗎? –

+0

我自己解決了。問題是我沒有正確寫入數據結構。 JSON數據結構:items = [{name:'xxx',value:'first'},...] 但是我用 ... ng-options =「item.id as item.value for item in items ... 我應該寫名字而不是id 謝謝!! – Alex

0

你應該能夠通過ngModel設置默認值。見this answer有關ngOption設置默認值:

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

 
app.controller('optionsCtrl', function($scope) { 
 
    $scope.prop = { 
 
    "type": "select", 
 
    "name": "Service", 
 
    "value": "Service 3", 
 
    "values": ["Service 1", "Service 2", "Service 3", "Service 4"] 
 
    }; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app="optionsApp"> 
 

 
    <div ng-controller="optionsCtrl"> 
 
    <select ng-model="prop.value" ng-options="v for v in prop.values"></select> 
 
    </div> 
 

 
</div>

相關問題