【问题标题】:Issues with passing ng-model to custom directive and making it work将 ng-model 传递给自定义指令并使其工作的问题
【发布时间】:2015-07-29 21:45:18
【问题描述】:

我创建了一个自定义指令,该指令使用国家列表自动填充选择。该指令有一个预选隔离范围属性,如果设置为 true 将预选一个国家/地区。

ng-model 也作为隔离范围属性传递 问题是不会设置ng-model

谁能给我一些关于如何制作 <auto-countries> 指令的指示,以便我能够设置 ng-model

这是我的指令代码:

app.directive('autoCountries', function() {
    return {
        restict: 'E',
        controller: 'CountriesCtrl as ctrl',
        scope: {
            preselect: '=',
            ngModel: '='
        },
        template: [

            '<select ng-if="!preselect" ng-model="ngModel">',
                '<option value="">Select Country</option>',
                '<option ng-repeat="country in ctrl.countries" value={{country.name}}>',
                    '{{country.name}}',
                '</option>',
            '</select>',

            '<select ng-if="preselect" ng-model="ngModel">',
                '<option ng-repeat="country in ctrl.countries" ng-selected="ctrl.countryFromIP == country.name" value={{country.name}}>',
                    '{{country.name}}',
                '</option>',
            '</select>',
        ].join('')
    }
})

让事情变得更奇怪的是,在一个完全不使用预选的指令的更简单的版本中,ng-model 将被设置。

没有例子有点难以理解,所以这里有一个 Plunkr! http://plnkr.co/edit/e1HPgGQlne7Q4TcNJ9XT?p=preview

【问题讨论】:

  • 为了尽量减少这个问题被否决/投票以关闭主题的可能性,您应该在问题正文中包含说明问题的相关代码。仅链接代码可能会随着时间的推移而发生变化,从而使问题或潜在答案在未来对其他人的有用性降低。

标签: angularjs angularjs-directive angular-ngmodel isolate-scope angularjs-select


【解决方案1】:

您不应该在&lt;option&gt; 上使用ng-repeat,而应在&lt;select&gt; 上使用ng-options

  <select ng-model="ngModel" ng-options="country.name as country.name for country in ctrl.countries"></select>

http://plnkr.co/edit/ADTPOIKZnnt14lVcr8TN?p=preview

【讨论】:

  • 感谢您的快速回复,但恐怕您的带有 ng-options 的代码示例不起作用。
【解决方案2】:

您应该使用 ngOptions 而不是 ngRepeat。我分叉了dave's plnkr 并对其进行了一些调整。带和不带预选的模板如下所示:

'<select ng-model="ngModel" ng-options="country.name as country.name for country in ctrl.countries"></select>'

我在国家控制器而不是视图/模板中进行了预选,就像在 ngOptions 的 angular 文档中一样。

$scope.ngModel = $scope.preselect ? $scope.ngModel = vm.countries[3].name : "";

(如果 preselect 等于 true,则为 ngModel 设置默认值,否则设置空字符串 - javascript 三元运算符。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    • 2016-08-16
    • 1970-01-01
    • 2014-05-26
    • 1970-01-01
    相关资源
    最近更新 更多