如何访问指令范围内的 ng-repeat 项? [英] How do you access an ng-repeat item in a directive's scope?
本文介绍了如何访问指令范围内的 ng-repeat 项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你如何为这样的东西设置范围值:
<my-element ng-repeat="p in people" person='p'></my-element>
var myApp = angular.module('myApp',[]);myApp.directive('myElement', function(){返回 {限制:'E',模板:'<div>{{名称}}</div><div>{{ age }}</div>'}});函数 MyCtrl($scope) {$scope.people = [{ name: 'Mike', age: 20 },{name: 'Peter', age: 22 }];}
解决方案
如果设置范围值"是指让模板工作,那么
template: '{{ p.name }}<div>{{页面}}</div>'
由于 ng-repeat 的每次迭代都会创建一个新的子作用域,因此在该作用域上定义了 p
.由于您的指令没有创建隔离范围,因此您不需要属性 person
,因此这适用于上述内容:
<my-element ng-repeat="p in people"></my-element>
如果你想要一个隔离范围,使用
<my-element ng-repeat="p in people" person='p'></my-element>
和
return {限制:'E',范围: {人:'='},模板:'<div>{{person.name}}</div><div>{{person.age }}</div>'}
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>'
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>
and
return {
restrict: 'E',
scope: {
person: '='
},
template: '<div>{{ person.name }}</div> <div>{{ person.age }}</div>'
}
这篇关于如何访问指令范围内的 ng-repeat 项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文