将数组对象从控制器传递到AngularJS中的自定义指令

时间:2014-09-09 10:19:19

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

我试图将角度控制器中的对象数组传递给自定义指令元素并使用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
        }
    ];

});

Shareddirectives.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: '@'
        }

    };
});

息points.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跟踪,但错误不会出现而且不会重复

1 个答案:

答案 0 :(得分:3)

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

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

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