AngularJS:在ngRepeat中使用自定义指令

时间:2017-12-05 16:00:15

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

我有一个自定义指令,但在ngRepeat中使用它有问题。例如,在我下面的taco示例中,在ng-repeat属性中被别名为taco的对象似乎无法从指令的定义中获取。

app.tpl.html

<div ng-repeat="taco in tacoController.tacos">
    <taco></taco>
<div>

taco.directive.js

(function() {
    angular
        .module('food')
        .directive('taco', [
            // DI: strings here
            function(
                // DI: params here
            ) {
                return {
                    restrict: 'E',
                    template: `
                        // THIS WORKS
                        <div>{{ tacoController.lastShipment }}</div>
                        // THIS DOES NOT!
                        <div>{{ taco.shellType }}</div>
                    `
                };
            }
        ])
})();

P.S。如果可能的话,我想避免在我的指令中使用隔离范围。

1 个答案:

答案 0 :(得分:1)

您可以访问tacoController,因为它位于主页的范围内,并且您在自定义指令中没有隔离范围。
另一方面,taco中的ng-repeat项不在主页的范围内,因此无法在自定义指令中访问。

您可以在指令的隔离范围内传递taco项,如下所示(您可能已经知道):

(function() {
    angular
        .module('food')
        .directive('taco', [
            // DI: strings here
            function(
                // DI: params here
            ) {
                return {
                    restrict: 'E',
                    scope: {
                        tacoItem: '=',
                        lastShipment: '='
                    },
                    template: `
                        // THIS WORKS
                        <div>{{ lastShipment }}</div>
                        // THIS DOES NOT!
                        <div>{{ tacoItem.shellType }}</div>
                    `
                };
            }
        ])
})();

那么html应该是:

<div ng-repeat="taco in tacoController.tacos">
    <taco taco-item="taco" last-shipment="tacoController.lastShipment"></taco>
<div>
相关问题