小提琴:http://jsfiddle.net/zorro/U8HpP/2/
下面的代码不起作用。 如果我删除了转换和模板,它就会按预期工作。 我错过了什么?
<div ng-app="example">
<div ng-controller="TodoCtrl">
<div ng-repeat="car in carsOwned">
<h3>Owned car: {{car.brand}}</h3>
<div example-select ng-model="car">
<select ng-model="car" ng-options="carType.brand for carType in carTypes"></select>
<p>Why doesn't the select alter the owned car?</p>
</div>
</div>
</div>
function TodoCtrl($scope) {
$scope.carTypes = [{
brand: 'BMW',
value: 'bmw'
}, {
brand: 'Mercedes',
value: 'me'
}, {
brand: 'Fiat',
value: 'fi'
}];
$scope.carsOwned = [$scope.carTypes[0]];
}
angular.module('example', []).directive('exampleSelect', function () {
return {
transclude: true,
scope: {
car: '='
},
link: function (scope, elm, attrs, ctrl) {
console.log('alive');
},
template: '<div ng-transclude></div>'
};
});
答案 0 :(得分:2)
ng-transclude
创建子范围,因此您需要设置一个对象成员才能访问父范围变量
修改强>
为了避免在您的选择选项中放置一个空选项,您还需要根据Why does AngularJS include an empty option in select?设置初始值
<h3>Owned car: {{car.value.brand}}</h3>
<div example-select>
<select ng-model="car.value" ng-options="carType.brand for carType in carTypes" ng-init="car.value=carTypes[0]"></select>
</div>
答案 1 :(得分:2)
绑定到carsOwned[$index]
而不是car
有效:
<select ng-model="carsOwned[$index]" ng-options="carType.brand for carType in carTypes"></select>
但如果拥有多辆汽车,您将遇到麻烦,因为carsOwned
可能包含重复项并且会中断ng-repeat
。要解决此问题,请添加跟踪表达式:
<div ng-repeat="car in carsOwned track by $index">
以下是对小提琴的更新:http://jsfiddle.net/U8HpP/5/