【发布时间】:2015-06-14 00:50:35
【问题描述】:
我是一个老“后端”,对 Angular 和现代前端编程很陌生,但我必须学习......
我有以下问题:有一个包含几个不同人员属性的列表,这些属性是通过控制器响应中的 ng-repeat 创建的。这些值是可编辑的,但显示控件取决于属性的类型。例如,性别需要通过选择框进行编辑。选择框的选项是从 Rest-Server 获得的。 所以现在的主要问题是:如何为每个属性构建不同的选择框? 我尝试了以下代码,但不起作用:
<section class="contactProperty" ng-repeat="property in contactDetail.properties">
<table>
<tr>
<td>{{property.message}}</td>
<td rowspan=2>{{property.value}}
<script>
var lst = ContactDetailController.getClassification(property.type);
</script>
<input ng-show="{{property.displaystyle_id}}==1" type="text" ng-model="property.value"/>
<select ng-show="{{property.displaystyle_id}}==3" ng-model="property.value">
<option ng-repeat="opt in lst" value="{{opt.id}}">{{opt.message}}</option>
</select>
</td>
</tr>
<tr>
<td>
<select type="text" ng-model="property.status_id">
<option ng-repeat = "status in contactDetail.propertyStatus" value="{{status.id}}">{{status.message}}</option>
</select>
</td>
</tr>
</table>
</section>
Controller 是在顶层元素上定义的,代码如下
.controller('ContactDetailController',
['$scope', '$rootScope', 'ContactDetailService',
function ($scope, $rootScope, ContactDetailService) {
$scope.getContactDetail = function () {
ContactDetailService.getContactDetail(function(response) {
if(response.success) {
$scope.contactDetail=response;
} else {
$scope.error = response.message;
}
});
};
$scope.getClassifications= function(type) {
ContactDetailService.getClassifications(type, function(response) {
if (response.success) {
return response;
}
});
};
$scope.getContactDetail();
}]);
以及对应的服务:
.factory('ContactDetailService',
['$http', '$rootScope', '$location',
function ($http, $rootScope, $location) {
var service = {};
service.getContactDetail = function(callbackFunc) {
delete $http.defaults.headers.common['X-Requested-With'];
var apiRoot="";
apiRoot = $rootScope.environments[window.location.host];
$rootScope.apiRoot=apiRoot;
var id=$location.search().id;
$http.get(apiRoot+'/contactdetail?id='+id, {})
.success(function(response){
$rootScope.contactDetail=response;
callbackFunc(response);
}).error(function(response){
alert("error"+response.message);
});
};
service.getClassifications = function(type, callbackFunc) {
var apiRoot="";
apiRoot = $rootScope.environments[window.location.host];
$http.get(apiRoot+'/classifications?type='+type, {})
.success(function(response) {
callbackFunc(response);
})
.error(function(response) {
alert("error"+response.message);
});
};
return service;
}]);
谁能帮帮我?
【问题讨论】:
-
你想要复选框还是下拉菜单?
-
我需要下拉菜单。性别只是一个例子。还有其他属性,例如位置或语言,肯定需要下拉菜单
-
如果我弄错了,请纠正。您有需要使用来自 REST 服务器的数据填充的下拉列表,对吗?在您的代码中,我看到您的输入和下拉字段具有相同的
ng-model="property.value"。我有点困惑。 -
是的,你是对的。下拉列表是从外部 ng-repeat 创建的,它呈现来自 contactDetail.properties 的所有属性。但是每个属性都需要不同类型的输入控件。例如生日的 DatePicker 或性别、语言等的下拉菜单。我正在寻找一种通用机制来通过 $http.get()-call 填充下拉列表,具体取决于 property.displaystyle_id 的值
-
您可以使用
ng-show/ng-hide或ng-if或ng-switch显示/隐藏字段,具体取决于您选择的变量类型。如果这是你想要的。
标签: angularjs select angularjs-ng-repeat