繁体   English   中英

指令中的ng-options

[英]ng-options in a directive

我想在指令中使用“ ng-options”。 首先让我向您展示一些代码:

fooController.js

        init();
        function init () {
            $scope.randomOptions = [{id: '1', name: 'AAA'},
                                    {id: '2', name: 'BBB'},
                                    {id: '3', name: 'CCC'},
                                    {id: '4', name: 'DDD'},
                                    {id: '5', name: 'EEE'}];
        }

index.html

<div sort-container ng-model="fooBy" opts="randomOptions"></div>

foob​​arDirective.js

    foobarDirective = function() {

        return {
            restrict: 'A',
            templateUrl: '/templates/directives/foobarDirective.html',
            transclude: true,
            scope: {
                opts        : '='
            }
        };

    };

foob​​arDirective.html

<select ng-options="item.id as item.name for item in opts"></select>

<div ng-repeat="item in opts track by $index">
     %(item.id)% - %(item.name)%
</div>

到目前为止,这就是我得到的。 但是ng-options仍然无法正常工作,除了我还有一些问题,这些问题可能有助于我进一步理解指令。

a)首先,我尝试通过DIV标签中的opts-attribute交付对象[$ scope.randomOptions],但这没有用。 我真的不希望完全不将对象写到parent.scope中,而只是将其粘贴为选项。

b)当我使用

opts : '@'
instead of
opts : '='

我可以删除不需要的双向绑定,但是无法以正确的方式传递对象。 “ @”是否还将我的对象定义为字符串?

感谢您帮助我:)

ng-options仅适用于随附的ng-model (我认为ng-repeat起作用吗?)

<select ng-model="selectedItem"
        ng-options="item.id as item.name for item in opts">

双向绑定确实是一种浪费(除非您计划在指令中修改选项)。 "@"是单向字符串绑定。

创建单向绑定的一种方法是使用"&" -这将创建一个函数,其结果是绑定表达式的结果。 因此,虽然使用"&"有点不直观,但这将为您提供单向绑定属性:

<foobar opts="randomOptions"></foobar>

然后,在指令内部使用如下:

<select ng-model="selectedItem"
        ng-options="item.id as item.name for item in opts()">

(注意最后的函数opts()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM