angularjs - 将数组对象从 Controller 传递到 AngularJS 中的自定义指令

标签 angularjs controller angularjs-directive angularjs-ng-repeat directive

我尝试将对象数组从 Angular Controller 传递到自定义指令元素,并使用 ng-repeat 迭代该对象,但出现以下错误:[ngRepeat:dupes]

home.js:

home.controller("homeController", function ($scope) {

    $scope.points =[

        {
            "url": '../assets/images/concert.jpg',
            "id":1
        },
        {
            "url": '../assets/images/dance.jpg',
            "id":2
        },
        {
            "url": '../assets/images/music.jpg',
            "id":3
        },
        {
            "url": '../assets/images/jazz.jpg',
            "id":4
        },
        {
            "url": '../assets/images/violin.jpg',
            "id":5
        },
        {
            "url": '../assets/images/music.jpg',
            "id":6
        }
    ];

});

共享指令.js:

var sharedDirectives = angular.module("sharedDirectives", []);


sharedDirectives.directive("interestPoints", function () {

    function link($scope, element, attributes, controller ) {

       $(element).find('#interest-points').owlCarousel({
           items : 4, //4 items above 1200px browser width
           itemsDesktop : [1200,3], //3 items between 1200px and 992px
           itemsDesktopSmall : [992,3], // betweem 992px and 768px
           itemsTablet: [850,2], //1 items between 768 and 0
           itemsMobile : [600,1] // itemsMobile disabled - inherit from itemsTablet option

       });
    }

    return {
        restrict: "E",
        templateUrl : "../html/views/interest-points.html",
        link: link,
        scope: {
            interestPoints: '@'
        }

    };
});

兴趣点.html:

<div id="interest-points" class="owl-carousel">
    <div ng-repeat="point in interestPoints" class="item">
        <img ng-src="{{point.url}}" alt="Owl Image"><h4>27<br>JUL</h4>

    </div>
</div>

home.html:

<div ng-controller='homeController'>
<interest-points interest-points="{{points}}""></interest-points>
</div>

我尝试通过 $index 进行跟踪,但错误没有出现并且不迭代

最佳答案

您正在使用 interestPoints: '@' 作为将 interestPoints 绑定(bind)到范围的方法。实际上,它仅将字符串 {{points}} 绑定(bind)到 interestPoints,而不是在父级范围内实际评估该表达式。

使用 interestPoints: '=' 作为绑定(bind)方法,然后使用 interest-points="points" 来获得所需的行为。

标题 Directive definition object 下的相关文档.

关于angularjs - 将数组对象从 Controller 传递到 AngularJS 中的自定义指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25742167/

相关文章:

java - 在 post 方法中从 Angular UI 发送两个参数并由 java API 处理

javascript - 如何使用 angularjs 以表格格式打印数组?

cocoa - AppDelegate 或 AppController

javascript - 通过模型初始化日期时间选择器上的日期

javascript - 使用 Angular.js 动态添加表格列

AngularJS : Isolating scope in a directive with transclude set to true

javascript - Angular.js ng-repeat 带条件

angularjs - 在 ng-grid 中自动填充 i18n 语言 - AngularJS

performance - MVC-Mini Profiler 与 DotTrace 不一致

error-handling - yii2要验证的尺寸并以表格形式显示错误消息