I've the AngularJS code below, where I'm trying to provide a callback function called callback
. I want to execute this method in my AngularJS code, but all possible ways I can think of fails, i.e something along the lines of
scope.callback();
scope.$apply(scope.callback());
What can I do in order to execute the provided callback (in this case someFunction
)?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script type="text/javascript">
// module
var starApp = angular.module('starApp', []);
// directive
starApp.directive('rating', function() {
// directive definition object
return {
// used as an attribute or element
restrict: 'AE',
// ng-class: for each key-value pair of the object with a truthy value the corresponding key is used as a class name
// ng-click: custom behavior when an element is clicked
// ng-repeat: update templates when collection items are inserted/removed
template: '<ul class="rating">' +
'<li ng-repeat="star in starArray" ng-class="star" ng-click="toggle($index)">' +
'\u2605' +
'</li>' +
'</ul>',
// variables in scope of directive (passed in from HTML)
scope: {
stars: '=stars', // '=' values of corresponding attributes
max: '=max',
callback: '&'
},
// executed after the template has been cloned and holds directive logic
link: function(scope, elem, attrs) {
var updateStars = function() {
scope.starArray = [];
for (var i = 0; i < scope.max; i++) {
scope.starArray.push({
filled: i < scope.stars
});
}
};
scope.toggle = function(index) {
scope.stars = index + 1;
};
scope.$watch('stars', function(oldValue, newValue) {
if (newValue) {
updateStars();
}
});
}
}
});
var someFunction = function() {
alert("test");
};
</script>
<link rel="stylesheet" href="rating.css"/>
</head>
<body ng-app="starApp">
<rating stars="3" max="5" callback='someFunction'/>
</body>
</html>