javascript - Updating an ng-repeat property in one controller based on the ng-repeat property of another controller? -
i have 2 separate angular controllers, 1 in main content area (homectrl
) showing list of events, , 1 in sidebar (sidebarctrl
) showing list of tags events.
// homectrl.js $scope.events = [{ name: "example event name", tags: [ { "id":7, "name":"imaginon", "following": "false" }, ] }];
in sidebar controller have collection of used tags:
// sidebarctrl.js $scope.tags = [ { "id":17, "name":"mintmuseum", "following": "true" }, { "id":7, "name":"imaginon", "following": "false" }];
i if user starts following tag in sidebar, tag gets highlighted in both sidebar , in home feed. if just trying highlight in sidebar easy enough:
// sidebar.html <div ng-repeat="tag in tags"> <li ng-class="{highlighted: tag.following}" ng-click="followtag(tag)">{{ tag.name }} </div>
but don't know how highlight instances of tag color in home feed. super easy in jquery giving each instance of tag in document class of tag_17
(or whatever id tag happened be) it'd nice avoid jquery , use angular's data binding paradigm if possible.
any suggestions?
create service, called highlightservice instance:
mymodule.factory('highlightservice', function() { var highlighted = []; var togglehighlight = function(tag) { var index = highlighted.indexof(tag); if(index > -1) { highlighted.splice(index, 1); } else{ highlighted.push(tag); } } return { highlighted: highlighted, highlight: highlight } });
inject service controller, assign local scope variable it:
$scope.highlightservice = highlightservice;
then in html:
<div ng-repeat="tags in highlightservice.highlighted"> <div ng-click="highlightservice.highlight(tag)></div> </div>
both controllers contain reference same object, see each other's changes on object during angular's $digest cycle, , updated appropriately.
alternatively make filter available in service, repeat on local array of tags filter provided service.
edit: here example of how that:
myapp.controller('highlightservice', [function() { var highlightedids = []; var ishighlighted = function(tag) { if(var index = highlightedids.indexof(tag.id) > -1) { return index; } else { return false; } } var highlight = function(tag) { var index = ishighlighted(tag.id); if(index) { highlightedids.splice(index, 1); } else { highlightedids.push(tag.id); } } return { ishighlighted: ishighlighted, highlight: hilight } }]).filter('highlighted', ['highlightservice', function(highlightservice) { return function(input) { if(highlightservice.ishighlighted(input) { return input; } else { return false; } }; }]);
use both service , filter in html appropriate.
Comments
Post a Comment