Reputation: 203
I'm trying to assign a controller per item of a list so that I'm able to manipulate the list item data. The displayed information differentiate for each item.
<div ng-repeat="item in items" ng-controller="ItemController">
{{item.name}}
<select ng-model="selectedSystem" ng-options="system.name for system in systems">
<button ng-click="dosomething()">do something</button>
</div>
How do I get the item inside of the ItemController
? I would like to set the list systems based on the information of the item inside of the ItemController
?
Can I move everything inside the divs into a template when using a ng-repeat
?
Thanks!
Upvotes: 1
Views: 223
Reputation: 203
I could solve the issue by using the suggested (@charlietfl and eddiec) directive solution.
Upvotes: 1
Reputation: 6900
In past experience, adding multiple controllers per item in an array is probably not the best way to approach the problem. Where do you have items defined? I assume there is some parent controller where you have that array requested through a service, or statically defined..
What needs to get the item inside the item controller? You have access to it, so you could just pass it into your function "doSomething()" if that's the route you want to go.
Here is the contents of my Controller.
$scope.items = [
{
name: "Name1",
systems: [
{name: 'System 1'},
{name: 'System 2'},
{name: 'System 3'}
]
},
{
name: "Name2",
systems: [
{name: 'System 4'},
{name: 'System 5'},
{name: 'System 6'}
]
}
];
$scope.doSomething = function(item){
console.log(item);
}
Here is the contents of my HTML
<div ng-controller="someController">
<div ng-repeat="item in items">
{{item.name}}
<select ng-model="selectedSystem" ng-options="system.name for system in item.systems"></select>
<button ng-click="doSomething(item)">do something</button>
</div>
</div>
End Result, gives a list of drop downs with the corresponding system and buttons that print out the item. I don't see any need for a controller per item...
Also, don't forget to follow indentation rules, and always use camelCase for your functions. Easier to read ;)
Upvotes: 0