是否可以使用ng-repeat从多个数组中扩展元素?

时间:2013-08-07 19:14:36

标签: angularjs angularjs-ng-repeat

我正在通过角度js工作,并与ng-repeat和指令进行摔跤。它看起来ng-repeat符号没有在指令的属性中扩展。我想做的是采用两个数组["a1", "a2", "a3"]["b1", "b2", "b3"]

我的标记看起来像这样:

<div ng-app="app">
    <div ng-controller="TestController">
        <div ng-repeat="a in as">
            <h2>{{a}}</h2> <!-- Works fine. -->
            <directive-test a="test" b="test"></directive-test>
            <div ng-repeat="b in bs">
                <h3>{{b}}</h3> <!-- Works fine. -->
                <directive-test a="{{a}}" b="{{b}}"></directive-test><!-- Does not work. -->
            </div>
        </div>
    </div>
</div>

并且支持javascript看起来像这样:

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

app.controller('TestController', ['$scope', '$window', function ($scope, $window) {
    $scope.as = ['a1', 'a2', 'a3'];
    $scope.bs = ['b1', 'b2', 'b3'];
}]);

app.directive('directiveTest', function () {
    return {
        restrict: "E",
        replace: true,
        transclude: true,
        scope: true,
        template:
            '<div>{{a}} by {{b}}</div>',
        controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {
            $scope.a = $attrs.a;
            $scope.b = $attrs.b;
        }]
    };
});

我希望展开{{a}}{{b}}并看到输出“a1 by b1”,相反,我会看到{{a}} by {{b}}之类的输出。有没有办法扩展ng-repeat元素以用作自定义指令的属性?

JSFiddle here.

2 个答案:

答案 0 :(得分:2)

这是我的版本:http://jsfiddle.net/FE3Tg/

我删除了控制器,只是从父作用域复制ab

<div ng-app="app">
  <div ng-controller="TestController">
    <div ng-repeat="a in as">
      <directive-test a="a" b="'test'"></directive-test>
      <div ng-repeat="b in bs">
        <directive-test a="a" b="b"></directive-test>
      </div>
    </div>
  </div>
</div>

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

app.controller('TestController', ['$scope', function ($scope) {
    $scope.as = ['a1', 'a2', 'a3'];
    $scope.bs = ['b1', 'b2', 'b3'];
}]);

app.directive('directiveTest', function () {
    return {
        restrict: "E",
        scope: {
            a: '=',
            b: '='
        },
        template: '<div>{{a}} by {{b}}</div>',
        replace: true
    };
});

答案 1 :(得分:1)

使用$scope.$parent代替$attrs,因为您应该从scope而不是attr访问模型。由于ng-repeat创建了新范围,因此您需要$parent来访问转发器中定义的模型。

controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {
    $scope.a = $scope.$parent.a; //change to $scope.$parent
    $scope.b = $scope.$parent.b; //change to $scope.$parent
}]