【发布时间】:2016-03-20 08:55:49
【问题描述】:
我有一个创建选择列表的指令。我需要传入对象的 id 和 value 键,因为这是一个可重用的控件。为什么更新时列表没有绑定到其父模型?
http://plnkr.co/edit/KHALRK1fBigZ2dj3bSlT?p=preview
index.html
<!doctype html>
<html ng-app="app">
<head>
</head>
<body>
<div ng-controller="Ctrl">
<my-dir list="characters"
model="model.character"
selected-item="model.character.id"
value-key="id"
text-key="name">
</my-dir>
<button ng-click="check()">Check</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
<script src="script.js"></script>
</body>
</html>
script.js
var app = angular.module('app', []);
app.controller('Ctrl', function($scope) {
$scope.model = { character: { id: 2, name: 'Link' } };
$scope.characters = [
{ id: 1, name: 'Mario' },
{ id: 2, name: 'Link' },
{ id: 3, name: 'Bowser' }
];
$scope.check = function() {
alert($scope.model.character.name);
};
});
app.directive('myDir', function() {
return {
restrict: 'E',
controller: function($scope) {
},
template: "<select ng-model='vm.model'>"
+ "<option value=''></option>"
+ "<option ng-repeat='item in vm.list' ng-selected='item[vm.valueKey]===vm.selectedItem' "
+ "value='item[vm.valueKey]' ng-bind='item[vm.textKey]'>"
+ "</option>"
+ "</select>",
controllerAs: 'vm',
bindToController: true,
scope: {
model:'=',
list:'=',
valueKey:'@',
textKey:'@',
selectedItem:'='
}
};
});
编辑:
这行得通,但是除非有人可以提出建议,否则有空白选项会有点混乱?
<select ng-model="vm.model" ng-options="item as item[vm.textKey] for item in vm.list track by item[vm.valueKey]"></select>
编辑 2:
有没有办法添加到视图中,以便空白选项实际绑定到模型并使其属性为 null,而不是使实际模型等于 null?
因此,对于给定的示例,空白值实际上应该如下所示:
$scope.model = { character: { id: null, name: null } };
不喜欢
$scope.model = { character: null };
当我们从列表中选择那个空白值时会发生什么。由于这是一个可重用的控件,因此在此处添加它会更整洁,而不是修改每个对象数组的所有源数据以添加该空值。
我已经解决了这个问题:
<select ng-model="vm.model" ng-change="selectChange()" ng-options="item as item[vm.textKey] for item in vm.list track by item[vm.valueKey]">
<option value=""></option>
</select>
...
$scope.selectChange = function () {
if ($scope.vm.model === null) {
var blankItem = {};
blankItem[$scope.vm.valueKey] = null;
blankItem[$scope.vm.textKey] = null;
$scope.vm.model = blankItem;
}
};
【问题讨论】:
-
我认为你应该通过一个服务来存储共享列表
-
如果你想绑定到它的模型,你不能在一个选择上使用
ng-repeat,你必须使用ng-options -
@Daniel_L 谢谢。我已更新问题以包括
ng-options。添加空白值的最干净的方法是什么?传递给此指令以添加我缺少的空白选项的任何选项? -
@masa 啊,谢谢....我没想过在指令中添加内容,但它当然会转置它。将添加此作为答案。谢谢大家!
标签: javascript angularjs angularjs-directive