Hawk
Hawk

Reputation: 1523

ng-model doesn't bind properly in directive template's select

See fiddle http://jsfiddle.net/5FdgC/2

var myModule = angular.module('myModule', [])
    .controller('MyCtrl', ['$scope', function ($scope) {


        $scope.model = { name: ' hans', game: 'wow' };

        $scope.items = [{ name: ' jens', game: 'wow' }, { name: ' hans', game: 'wow' }];

        $scope.equal = angular.equals($scope.items[1], $scope.model);

    }]);

myModule.directive('selectBlock', function () {

    return {
        restrict: 'A',
        replace: true,
        template: '<select ng-model="model" ng-options="item.name for item in items"></select>',

        scope: {
            model: '=',
            items: '='
        },
        link: function (scope, element, attributes) {
        }
    }
});

Problem:

I pass a model and some items. model angular.equals to true with an object in items. However, setting ng-model="model" in the select does not display model in the dropdown. It remains blank with the items listed beneath.

Say

items = [ob1, ob2]
angular.equals(ob2, model) = true
ng-model="model"

select renders as

--blank--  //selected value
ob1
ob2

instead of

ob1
ob2 // selected value

Cheers

Upvotes: 2

Views: 2617

Answers (1)

Utopik
Utopik

Reputation: 3783

Ok, I have found the problem.

http://jsfiddle.net/5FdgC/3/

.controller('MyCtrl', ['$scope', function ($scope) {

    $scope.items = [{ name: ' jens', game: 'wow' }, { name: ' hans', game: 'wow' }];
    // here, you have to set the default by reference, not by value.
    $scope.model = $scope.items[1];
[...]

Upvotes: 2

Related Questions