我正在通过角度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元素以用作自定义指令的属性?
答案 0 :(得分: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
};
});
答案 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
}]