使用angular.js设置从JSON文件中的动态值中选择

时间:2015-08-22 15:28:23

标签: json angularjs

如果这是一个新手问题,请原谅我。我对Angular很新。

我到处寻找这个,虽然有很多问题已经回答了关于设置默认选项的问题,但我找不到设置所选选项的问题动态地来自JSON文件中的值。

我的控制器看起来像这样:

peopleControllers.controller('PeopleListCtrl', ['$scope','PeopleList',
function($scope, PeopleList) {
    $scope.id = 'id';
    $scope.people = PeopleList.query();
    $scope.orderProp = 'name';
    $scope.comments = 'comments';
    $scope.department = 'department';
    $scope.departmentList = [
        {id : 1, name : "HR" },
        {id : 2, name : "Accounting"},
        {id : 3, name : "Marketing"}
    ];
}]);

PeopleList 是来自JSON文件的$资源,其格式如下:

[
{
    "id": "johnasmith",  
    "name": "John A. Smith",
    "department": "1",
    "comments": "Good worker"
},
{
    "id": "sarahqpublic",  
    "name": "Sarah Q. Public",
    "department": "2",
    "comments": "New hire"
},
{
    "id": "janedoe",  
    "name": "Jane Doe",
    "department": "3",
    "comments": "Good resource for information"
}
]
...

在HTML中,我有这个:

ul class="people">
    <li ng-repeat="person in people | filter:query | orderBy:orderProp">
        <a href="#/people/{{people.id}}"><h3>{{people.name}}</h3></a>
        <p>{{people.comments}}</p>
        <select ng-model="department" ng-options="departmentList.name for department in departmentList track by department.id">
        </select>
    </li>
</ul>

select语句使用departmentList中的所有正确信息填充,但其选定的值最终为空。如果我为$ scope.department设置一个静态值,比如$scope.department = $scope.departmentList[1];(对于&#34; Accounting&#34;)它可以很好地工作。但它似乎无法从JSON文件中提取部门值。

我知道我错过了一些简单而明显的东西。必须有其他人已经问过并回答了这个问题,所以如果结果是重复,我很抱歉。但我现在真的很沮丧。

2 个答案:

答案 0 :(得分:1)

您的JSON文件只包含导致您在数组中搜索值"3"而不是选择[3]的字符串。因此,请将您的JSON更改为department: 3而不是department: "3",依此类推。

像这样:

{
    "id": "johnasmith",  
    "name": "John A. Smith",
    "department": 1,
    "comments": "Good worker"
},
{
    "id": "sarahqpublic",  
    "name": "Sarah Q. Public",
    "department": 2,
    "comments": "New hire"
},
{
    "id": "janedoe",  
    "name": "Jane Doe",
    "department": 3,
    "comments": "Good resource for information"
}

你也应该select ng-model="person.department"

答案 1 :(得分:1)

  

From Docs

     

选择as并跟踪不要同时使用select as和track by   表达。它们并非旨在协同工作。

此外,@ Chrillewoodz建议您需要将部门string的{​​{1}}转换为number

<强>标记

id

Demo Plunkr