javascript - 如何将任何数组从 ng-repeat 传递到 AngularJs 属性指令?

标签 javascript angularjs directive

我有一个菜单项层次结构列表,其中每个项目都有一个子列表。对于 menuItems 属性来自 Controller 范围(父级列表)。我想传递一个数组以供以下示例的两个级别上的指令使用。

HTML代码

<div sortable="menuItems">
    <div ng-repeat="item in menuItems">
        ...
        <div sortable="item.Children">
            <div ng-repeat="child in menuItems.Children">...</div>
        </div>
    </div>
</div>

指令代码

app.directive('sortable', function ($timeout) {
    return {
        restrict: 'A',
        link: function($scope, $elem, attrs) {
         // I need access by the array in here.
        }
    };
});

我已将可排序属性设置为列表名称的值,这显然不适合我。

最佳答案

您可以设置范围监视(或集合监视),因为属性的值是范围表达式。

app.directive('sortable', function ($timeout) {
    return {
        restrict: 'A',
        link: function($scope, $elem, attrs) {
             $scope.$watchCollection(attrs.sortable, function (newCollection, oldCollection) {
                 // (do something with newCollection)
             });
        }
    };
});

关于javascript - 如何将任何数组从 ng-repeat 传递到 AngularJs 属性指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36025677/

相关文章:

javascript - 如何在 angularjs 应用程序中包含 d3.js?

测试直接使用服务的 AngularJS 指令

javascript - jQuery 淡入淡出停止错误 : jQuery (".box"). stop().fadeIn();

javascript - AngularJS 指令模板未渲染

javascript - 在元素悬停时显示 div,以便 div 内的元素应该是可点击的

angularjs - Node 。 npm 安装后找不到 gulp

javascript - 在 ng-include 中使用变量作为表达式

css - 符号::在 css 之后,在 Angular 5 指令中不起作用

javascript - Highcharts 和 EXTJS 3 : Labels in x axis overlap

javascript - 从页面禁用浏览器打印选项(页眉、页脚、边距)?