0

Fiddle: http://jsfiddle.net/zorro/U8HpP/2/

Below code does not work. If I remove the transclude and template, it works just as intended. What am I missing?

    <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>'
        };
    });
Soroush Hakami
  • 5,226
  • 15
  • 66
  • 99

2 Answers2

2

ng-transclude creates a child scope, so you need to set an object member in order to access the parent scope variable


EDIT

In order to avoid having an empty option placed in your select options, you also need to set an initial value as per 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

Community
  • 1
  • 1
Marc Kline
  • 9,399
  • 1
  • 33
  • 36
2

Binding to carsOwned[$index] instead of car works:

<select ng-model="carsOwned[$index]" ng-options="carType.brand for carType in carTypes"></select>

But you will have trouble if multiple cars are owned, because carsOwned may contain duplicates and break ng-repeat. To fix this, add a tracking expression:

<div ng-repeat="car in carsOwned track by $index">

Here is an update to your fiddle: http://jsfiddle.net/U8HpP/5/

j.wittwer
  • 9,497
  • 3
  • 30
  • 32