I have a pretty simple itemController which contains an array of items (in actuality, these are obtained from an API). I want to then call the API again to get the subsections based on what is selected from the itemForm.item select (i.e., get all subsections for itemForm.item.id).
When I select Item1 (id=1), I want to update the form to include the subsections for that item.id. The problem I am having is how exactly to pass the itemForm.item.id into the sectionController. As you can see below, I tried it with $attrs, but this ends up passing in a string of "{{itemForm.item.id}}" instead of the actual value.
I am new to Angular and am quite possibly going about this wholly the wrong way, so please let me know if I am totally off base in my approach.
Javascript
angular.module('app').controller('itemController', function(){
this.items = [
{
"id": 1,
"name": "Item1"
},
{
"id": 2,
"name": "Item2"
},
{
"id": 3,
"name": "Item3"
}
];
}];
angular.module('app').controller('sectionController',
['SectionService', '$attrs',
function(SectionService, $attrs){
var store = this;
SectionService.getSections($attrs.id)
.then(function(data) {
store.sections = data;
}, function(error) {
// promise rejected
console.log(error);
});
}]);
HTML
<div class="form-group" ng-controller="itemController as item">
<select ng-model="itemForm.item" ng-options="item as item.name for item in item.items track by item.id" required>
</select>
<!-- this is just a test to try to get the behavior to work correctly -->
<div ng-controller="sectionController as section" id="{{$itemForm.item}}">
<p ng-repeat="section in section.sections">{{section.name}}</p>
</div>
</div>
The SectionService is a factory which simply calls the API and returns a JSON array such as this for a particular itemID (itemID=1 in this case):
[
{
"name": "Section1",
"itemID": 1,
"sectionID": 1
},
{
"name": "Section2",
"itemID": 1,
"sectionID": 2
},
{
"name": "Section3",
"itemID": 1,
"sectionID": 3
},
{
"name": "Section4",
"itemID": 1,
"sectionID": 4
}
]