ng-model在指令模板的选择中没有正确绑定

时间:2013-09-10 12:12:05

标签: angularjs angularjs-directive

请参阅小提琴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) {
        }
    }
});

问题:

我传递了一个模型和一些项目。使用项目中的对象将angular.equals模型设置为true。但是,在选择中设置ng-model =“model”不会在下拉列表中显示模型。下面列出的项目仍为空白。

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

选择渲染为

--blank--  //selected value
ob1
ob2

而不是

ob1
ob2 // selected value

干杯

1 个答案:

答案 0 :(得分:2)

好的,我发现了问题。

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];
[...]