我将对象信息传递给我的自定义指令时出现问题,该指令具有隔离范围。我把问题归结为这个简单的plnkr,以展示我正在打击的墙:
http://plnkr.co/edit/oqRa5pU9kqvOLrMWQx1u
我只是错误地使用ng-repeat和指令吗?同样,我的目标是将对象信息从ng-repeat循环传递到我的指令中,该指令将具有自己的范围。
HTML
<body ng-controller="MainCtrl">
<ul>
<li ng-repeat="i in items", my-directive="i">
<span>{{$index}}</span>
<p>{{item.name}}</p>
<p>{{item.value}}</p>
</li>
</ul>
</body>
JS
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.items = [
{name: "Name #1", value: "Value #1"},
{name: "Name #2", value: "Value #2"},
{name: "Name #3", value: "Value #3"}
];
});
app.directive('myDirective', function($scope) {
return {
restrict: "A",
scope: { item: "=myDirective" },
link: function(scope, elem, attrs) {
}
}
});
谢谢。
答案 0 :(得分:1)
的问题:
$scope
ng-repeat
为元素提供新属性,例如value
,但my-directive="i"
也可以。
<强> HTML 强>
<ul>
<li ng-repeat="i in items" my-directive value="i">
<span>{{$index}}</span>
<p>{{item.name}}</p>
<p>{{item.value}}</p>
</li>
</ul>
<强> JS 强>
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.items = [
{name: "Name #1", value: "Value #1"},
{name: "Name #2", value: "Value #2"},
{name: "Name #3", value: "Value #3"}
];
});
app.directive('myDirective', function() {
return {
restrict: "A",
scope: { item: "=value" },
link: function(scope, elem, attrs) {
console.log(scope.item);
}
}
});
演示 Plunker