Saturday, March 22, 2014

AngularJS and Starrr plugin: updating score variable with directives

I'm using Starrr plugin (https://github.com/dobtco/starrr) with Angular.JS.

When the star rating changes, 'starrr:change' dom event is fired. I have to catch this event and update the score variable in my angular.js scope.  It was hard to find it but found it:
We define a directive in our angular app js file:
myApp.directive('rateable', function(){
        return function(scope, elt, attr){
            elt.bind('starrr:change', function(e, value){
                scope.score = value;
                scope.$apply();
            });
        }
});
In the HTML Code, we use the rateable directive as HTML tag attribute:
<div class="starrr" data-rating="1" id="hearts" rateable></div>
This way, whenever "starrr:change" event is fired from "#hearts", our score variable in the scope is updated. We have to call $apply to let Angular know some changes has been proposed.

No comments: