I am currently working on a tag-manager feature within an angular form that utilizes two dropdown menus (in this example, a food category and a specific item). The functionality I am aiming for is when a user selects a food category, the item dropdown should appear. When a value is chosen from the dropdown, I want to append a string to my tag list in the format of ': '. Below you can find the code:
app.js
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope){
$scope.tags = [];
$scope.userCategory;
$scope.userFood;
$scope.primaryFoods = [
{
'id': 1,
'parent_id': null,
'name': 'Pizza'
},
{
'id': 4,
'parent_id': null,
'name': 'Burgers'
},
{
'id': 7,
'parent_id': null,
'name': 'Pasta'
},
];
$scope.secondaryFoods = [
{
'id': 2,
'parent_id': 1,
'name': 'Cheese Pizza'
},
{
'id': 3,
'parent_id': 1,
'name': 'Combo Pizza'
},
{
'id': 5,
'parent_id': 4,
'name': 'Cheese Burgers'
},
{
'id': 6,
'parent_id': 4,
'name': 'Hamburgers'
},
];
});
app.directive('doubleTagManager', function() {
return {
restrict: 'E',
scope: {tags: '=', primary: '=', secondary: '=', userPrimary: '=', userSecondary: '='},
templateUrl: 'double-tag-manager.html',
link: function ($scope, $element) {
var input = angular.element($element.find('select')[1]);
// This adds the new tag to the tags array in '<Primary>: <Secondary>' format
$scope.add = function() {
var new_value = input[0].value;
if ($scope.tags.indexOf(new_value) < 0) {
$scope.tags.push($scope.userPrimary.name + ': ' + $scope.userSecondary.name);
}
};
// This is the ng-click handler to remove an item
$scope.remove = function (idx) {
$scope.tags.splice(idx, 1);
};
input.bind( 'change', function (event) {
$scope.$apply($scope.add);
});
}
};
});
double-tag-manager.html
<div class="row">
<div class="col-md-6">
<select name="uFoodsPrimary" id="foodPrimary" class="form-control"
ng-model="userPrimary"
ng-options="item.name for item in primary track by item.name" required>
<option value="">Select a Food category!</option>
</select>
</div>
<div class="col-md-6" ng-show="userPrimary">
<select name="uFoodsSecondary" id="foodSecondary" class="form-control"
ng-model="userSecondary"
ng-options="item.name for item in (secondary | filter: {parent_id: userPrimary.id})
track by item.name"
required>
<option value="">Select a Food sub-category!</option>
</select>
</div>
</div>
<div class="tags">
<a ng-repeat="(idx, tag) in tags" class="tag" ng-click="remove(idx)">{{tag}}</a>
</div>
One additional feature I would like to include is the option for users to select 'All foods' so they don't have to individually select each item. I'm facing some challenges figuring out how to add this extra field using ng-options.
BONUS: If a category without any children is selected, I would like it to be automatically added to the tags list.