0

I'm working my way through angular js, and wrestling with ng-repeat and directives. It looks ng-repeat symbols aren't expanded in the attributes of directives. What I'd like to do is take two arrays ["a1", "a2", "a3"] and ["b1", "b2", "b3"]

My markup looks like this:

<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>

and the backing javascript looks like this:

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;
        }]
    };
});

I'd expect the {{a}} and {{b}} to be expanded and see output like "a1 by b1", but instead, I see output like {{a}} by {{b}}. Is there a way to expand ng-repeat elements to use as attributes of custom directives?

JSFiddle here.

4

2 回答 2

2

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

我删除了控制器,只是从父范围复制a和:b

<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
    };
});
于 2013-08-07T19:36:29.620 回答
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
}]
于 2013-08-07T19:24:38.540 回答