When you click on one button, it triggers the other. In my application, clicking on categories changes the URL to /:catId, which populates the list of animals where animal.catId = catId. I've tried organizing the arrays within functions or objects but they still seem to trigger each other. It appears that both buttons are pointing to the same object in the scope or model. How can I separate them? Is it reasonable to process both lists in the same factory?
This is the HTML:
<div ng-controller="MyCtrl">
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
Categories<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li ng-repeat="category in animals.categories"><a>{{category}}</a></li>
</ul>
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
Animals <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li ng-repeat="category in animals.all"><a>{{animal}}</a></li>
</ul>
</div>
</div>
And here is the Javascript:
var myApp = angular.module('myApp', []);
myApp.factory('animals', function(){
var data =
[
{category: "mammal", name: "dog", categoryID: "MAM"},
{category: "fish", name: "pickerel", categoryID: "FIS"},
{category: "mammal", name: "cat", categoryID: "MAM"},
{category: "mammal", name: "monkey", categoryID: "MAM"},
{category: "bird", name: "budgie", categoryID: "BIRD"}
];
var collect_categories = function(o, e) {
o[e.categoryID] = e.category;
return o;
};
var unpack = function(name, id) {
return { name: name, catID: id };
};
var all = [];
var categories = [];
var init = function() {
_(data).each(function(item) {
all.push({
title: item.name,
})
});
_(data).chain()
.reduce(collect_categories, {})
.map(unpack)
.each(function(cat) { categories.push(cat)})
.value();
}();
return {
all: all,
categories: categories
}
});
function MyCtrl($scope, animals){
console.log("animals", animals);
$scope.animals = animals;
}
MyCtrl.$inject = ['$scope', 'animals'];