选择in指令,转换不更改父范围

时间:2014-04-30 14:50:36

标签: angularjs angularjs-directive angularjs-scope

小提琴: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>'
        };
    });

2 个答案:

答案 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>

Updated Fiddle

答案 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/