0

...同时维护模型绑定?

我有一个像这样的选择菜单:

<select class="form-control" ng-model="activeTask" ng-options="task.title for task in tasks"> </select>

这会填充一些文本,如下所示:

<span>{{activeTask.title}}</span>

Projects资源在此处获取一些 json(工作正常):

function TimerCtrl($scope, Projects) {
    $scope.projects = Projects.get({}, {isArray:true}, function(projects) {
        $scope.tasks = $scope.projects[0].tasks;
        $scope.activeProject = $scope.projects[0];
        $scope.activeTask = $scope.tasks[0];
    });
}

这是Projects服务(也可以正常工作):

angular.module('projectServices', ['ngResource']).
factory('Projects', function($resource) {
    return $resource('data/projects.json', {}, {
        get: {method:'GET', isArray:true}
    });
});

这是JSON(也很好):

[
    {
        "title":"Chores",
        "url_title":"chores",
        "category":"Home",
        "tasks": [
            {"title":"Cleaning", "url_title":"cleaning"},
            {"title":"Yard Work", "url_title":"yard_work"},
            {"title":"Walking the Dogs", "url_title":"url_title"}
        ]
    },
    {
        "title":"Personal Website",
        "url_title":"personal_website",
        "category":"Work",
        "tasks": [
            {"title":"Design", "url_title":"design"},
            {"title":"Front End Dev", "url_title":"front_end_dev"},
            {"title":"Node Dev", "url_title":"node_dev"},
            {"title":"PHP Dev", "url_title":"php_dev"}
        ]
    }
]

Angular 自动创建的数值一切正常。我的问题是......值需要是对 url 友好的字符串task.url_title,但选项文本应该是task.title.

任何帮助将不胜感激。我想去喝啤酒!

所以,这是我采用的解决方案:

我使用task对象本身作为值,如下所示:

<select class="form-control" ng-model="activeTask" ng-options="task as task.title for task in tasks">

这使我可以轻松绑定跨度值以显示任务title,而不是url_title

<span>{{activeTask.title}}</span>

感谢@sza 为我指明了正确的方向。他的建议在正确答案的评论中。

4

2 回答 2

1

您可以将理解表达式更改为

ng-options="task.url_title as task.title for task in tasks"

Working Demo

于 2013-09-04T22:57:49.697 回答
0

你需要使用ng-options="...". 还要使用ng-model="...",否则将无法正常工作。

这是它的细分:

<select ng-options="ITEM.VALUE as ITEM.LABEL for ITEM in ITEMS" ng-model="val">
  <option>placeholder value which goes at the top of the element</option>
</select>
于 2013-09-04T23:04:52.630 回答