问题
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 }];
}
回答1:
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>'
}
回答2:
I like to use '@' when defining the directive scope. This enables the directive isolated scope to access p, for example in link:
return {
scope: '@',
link: function(scope) {
console.log(scope.p); //It can now be accessed because of '@'
}
}
回答3:
you do not need to create an isolated scope in the directive. ng repeat will do this automatically for you. so just remove:
in the directive:
scope: {
person: '='
},
and in the ng repeat html markup:
person='p'
in your directive you will be able to access something like
$scope.p.personAttribute
like mentioned in the explanation here: angularjs-pass-instance-of-each-ng-repeat-in-html-to-directive
来源:https://stackoverflow.com/questions/14657591/how-do-you-access-an-ng-repeat-item-in-a-directives-scope