Friday 15 June 2012

javascript - How to handle events among multiple directives and a controller? -



javascript - How to handle events among multiple directives and a controller? -

i'm struggling come proper angular idiom, , felt path going downwards non-pure on. frame scenario contrived example:

consider angular controller, called albumcontroller.

albumcontroller has scope property, array of album objects:

$scope.albums = [ { title : "album 1", artist : "artist 1" }, ... ]

i'm using ng-repeat paired custom directive layout albums:

<div ng-repeat="album in albumns"> <div fresh-album album="album"></div> </div>

and directive template setting property on album object:

module.directive('freshalbum', function() { homecoming { template : '<button ng-click="album.selected = !album.selected">click</button>', scope : { album = '=' }, ... }; });

note, reason adding selected attribute when album clicked, custom styles indicate album selected, added element.

what is: when album selected, deselect other selected album (e.g., if album 1 selected, , user selects album 2, need album 1 deselect).

my initial thought have $watch in albumcontroller monitor album changes:

var selectedalbum = -1; // keeping track of selected album $scope.$watch('albums', function(newvalue) { angular.foreach($scope.albums, function(album, i) { if (selectedalbum === -1 && album.selected) { selectedalbum = i; // no selected albums } else if (selectedalbum === && album.selected) { album.selected = false; // selected album; deselect } else if (album.selected) { selectedalbum = i; // newly selected album } }); });

however, because i'm "de-selecting" albums in $watch callback, triggers $watch, deselecting newly selected album well. @ point, stopped, because felt approaching wrong.

an alternative thought had have freshalbum directive publish "selection" event controller responds to. approach more angular-esque"?

you can add together look directive called whenever album clicked.

module.directive('freshalbum', function() { homecoming { template : '<button ng-click="album.selected = !album.selected; albumisclickedevent();">click</button>', scope : { album : '=' albumisclicked: "&"}, ... }; }); <div ng-repeat="album in albumns"> <div fresh-album album="album" album-is-clicked="albumisclickedevent"></div> </div>

and in controller, can implement albumisclickedevent function want accomplish (close other open albums etc.).

through look directive can communicate outer controller.

javascript angularjs

No comments:

Post a Comment