您如何在指令范围内访问ng-repeat项目? [英] How do you access an ng-repeat item in a directive's scope?
本文介绍了您如何在指令范围内访问ng-repeat项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何为以下内容设置作用域值:
How do you set the scope value for something like this:
<div ng-controller="MyCtrl">
<my-element ng-repeat="p in people" person='p'></my-element>
</div>
var myApp = angular.module('myApp',[]);
myApp.directive('myElement', function(){
return {
restrict: 'E',
template: '<div>{{ name }}</div> <div>{{ age }}</div>'
}
});
function MyCtrl($scope) {
$scope.people = [{ name: 'Mike', age: 20 },{name: 'Peter', age: 22 }];
}
推荐答案
如果通过设置范围值"来表示您可以使用模板,那么
If by "set the scope value" you mean have the template work, then
template: '<div>{{ p.name }}</div> <div>{{ p.age }}</div>'
由于ng-repeat的每次迭代都会创建一个新的子作用域,因此在该作用域上定义了p
.由于您的指令未创建隔离作用域,因此您不需要属性person
,因此可以与上面的方法一起使用:
Since each iteration of ng-repeat creates a new child scope, p
is defined on that scope. Since your directive is not creating an isolate scope, you don't need attribute person
, so this works with the above:
<my-element ng-repeat="p in people"></my-element>
如果要使用隔离范围,请使用
If you want an isolate scope, use
<my-element ng-repeat="p in people" person='p'></my-element>
和
return {
restrict: 'E',
scope: {
person: '='
},
template: '<div>{{ person.name }}</div> <div>{{ person.age }}</div>'
}
这篇关于您如何在指令范围内访问ng-repeat项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文