2016-03-08 74 views
2

NG选项我在JavaScript中动态默认值

$scope.prefixes = [ 
    {'id': 'Mr', 'name': 'Mr.'}, 
    {'id': 'Mrs', 'name': 'Mrs.'}     
]; 

这个结构,我得到,如果我的用户是先生或太太,像这样

JSON.parse(localStorageService.get("user")).prefix. 

根据数据,我得到,当用户登录所以用户的前缀总是动态的。

这是我收到如果用户是先生还是女士,把它在一个范围VAR,然后使用该范围VAR在HTML中的选择标签

$scope.prefixes = [ 
    {'id': 'Mr', 'name': 'Mr.'}, 
    {'id': 'Mrs', 'name': 'Mrs.'}     
]; 


    $scope.readPrefixesInit; 

    for (i = 0; i < $scope.prefixes.length; i++) { 
    //if dynamic is equal with one of the ids, get the name 
    if ($scope.prefixes[i].id == JSON.parse(localStorageService.get("user")).prefix){ 
     $scope.readPrefixesInit = $scope.prefixes[i].name;               
     } 
} 

设置的默认值的想法然后在HTML

<select required autofocus class="form-control"  
     ng-model="prefix" 
     ng-init="prefix = {{ readPrefixesInit }}" 
     ng-options="f.id as f.name for f in prefixes">   
     <option value="">Select Prefix</option> 
    </select> 

这是行不通的。

我得到这个错误Syntax Error: Token '{' invalid key at column 12 of the expression [prefix = {{ readPrefixesInit }}] starting at [{ readPrefixesInit }}].

我得到我的下拉但一直没有价值预选。

我该如何解决这个问题? 谢谢

+1

你在哪里定义“readPrefixes”?我只在你的代码中看到一个“前缀”数组 – chris

+0

@chris对不起,并感谢他的纠正。我编辑我的OP。 – slevin

回答

0

您的HTML部分中有语法错误。行:

ng-init="prefix = {{ readPrefixesInit }}" 

应该是:

ng-init="prefix = readPrefixesInit" 

其实你并不需要中间变量readPrefixesInit,并且可以使用prefix代替。

JS:

$scope.prefixes = [ 
    {'id': 'Mr', 'name': 'Mr.'}, 
    {'id': 'Mrs', 'name': 'Mrs.'}     
]; 

$scope.prefix = null; 

for (i = 0; i < $scope.prefixes.length; i++) { 
    //if dynamic is equal with one of the ids, get the name 
    if ($scope.prefixes[i].id == JSON.parse(localStorageService.get("user")).prefix) { 
     $scope.prefix = $scope.prefixes[i].name;               
    } 
} 

模板:

<select required autofocus class="form-control"  
     ng-model="prefix" 
     ng-options="f.id as f.name for f in prefixes">   
    <option value="">Select Prefix</option> 
</select> 

Click here的演示。