...同时维护模型绑定?
我有一个像这样的选择菜单:
<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 为我指明了正确的方向。他的建议在正确答案的评论中。