【问题标题】:How to bind the ng-repeat variable to a custom angular directive?如何将 ng-repeat 变量绑定到自定义角度指令?
【发布时间】:2016-11-24 13:14:39
【问题描述】:

在 Angular (v1.3) 中,如何将变量从 ng-repeat 绑定到自定义指令?

所有示例似乎都绑定到 $scope 变量。例如,给定一个产品列表和一个名为 product 的自定义指令,我们如何才能做到这一点:

<li ng-repeat="product in products">
    <product item="product" />
</li>

指令的创建位置:

(function () {
    'use strict';

    var productDirective = function () {
        return {
                restrict: 'E',
                scope: {item: '='},
                templateUrl: '/views/product.html',                 
            };
    };

    angular
        .module('myApp')
        .directive('product', productDirective);

})();

它有一个非常简单的模板:

<p>{{item.name}} {{item.price}}</p>

这失败了,因为 scope: '=' 只绑定到 $scope,而不绑定到 ng-repeat。

我能够让它与它一起工作

return {
            restrict: 'E',
            scope: {item: '@'},
            templateUrl: '/views/product.html',

            link: function(scope, element, attributes){
                scope.item = scope.$eval(attributes.item);
            }
        };

但是 $eval 的使用当然是不可接受的(不好的风格)。

实现此目的的正确角度方式是什么?

【问题讨论】:

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


    【解决方案1】:

    这失败了,因为 scope: '=' 只绑定到 $scope,而不绑定到 ng-repeat。

    我不太明白你上面所说的意思,但是当你从指令的父范围绑定 object 时,绑定上下文中的 = 很有用 - 这实际上是您使用 product 指令的控制器 - 到指令的隔离范围,而不是 ng-repeat

    因此,在您的情况下,您实际上不需要使用 $eval 技巧将对象从父控制器绑定到指令的隔离范围。

    只要确保在特定的 parent 控制器中正确定义了 products 数组即可。

    这是一个Demo,告诉你如何让它工作。

    【讨论】:

      【解决方案2】:

      这失败了,因为 scope: '=' 只绑定到 $scope,而不绑定到 ng-repeat。

      它应该失败,因为ng-repeat 会为每次迭代创建一个范围,并将当前的product 与其他循环变量(如$index)一起放入其中。所以product实际上是在作用域上,你可以正常绑定到它。

      我创建了一个FIDDLE 并没有更改您的代码来确认这一点。

      【讨论】:

        【解决方案3】:

        尝试将控制器添加到 productDirective:

         var productDirective = function () {
            return {
                    restrict: 'E',
                    scope: {item: '='},
                    templateUrl: '/views/product.html',
                    controller: ['$scope', function($scope) {}]
                };
         };
        

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-06
        • 1970-01-01
        • 1970-01-01
        • 2013-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-14
        相关资源
        最近更新 更多