Create a gist now

Instantly share code, notes, and snippets.

@bressain /moveFocus.html Secret
Last active Aug 29, 2015

What would you like to do?
Creating External Hooks In AngularJS Directives Files
<script>
$(function () {
$('#my-widget').on('comment.click', function (data) {
alert('comments was clicked with\nobjectId: ' + data.objectId + '\nobjectTypeId: ' + data.objectTypeId);
});
});
</script>
link: function (scope, element, attrs) {
element.find('.buttonL').on('click', function () {
element.triggerHandler($.Event('comment.click', { objectId: scope.objectId, objectTypeId: scope.objectTypeId }));
});
}
'use strict';
angular.module('comment-widget', []);
angular.module('comment-widget').factory('commentService', ['$http', '$q', '$window', function ($http, $q, $window) {
return {
getInitData: function (objectId, objectTypeId) {
var deferred = $q.defer();
$http.get('initdata?objectid=' + objectId + '&objecttypeid=' + objectTypeId)
.success(function (data) {
deferred.resolve(data);
})
.error(function () { deferred.reject({ commentCount: 0, resourceStrings: { commentButton: 'Comment' } }); });
return deferred.promise;
},
getCommentCounts: function (objectId, objectTypeId) {
var deferred = $q.defer();
var payload = { "objects": [{ "objectId": objectId, "objectTypeId": objectTypeId }] };
$http.post('counts', payload)
.success(function (data) {
deferred.resolve(data.counts.length > 0 ? data.counts[0].count : 0);
})
.error(function () { deferred.reject(0); });
return deferred.promise;
}
};
}]);
angular.module('comment-widget').controller('CommentCtrl', ['commentService', '$scope', function (commentService, $scope) {
initialize();
$scope.refreshComments = function () {
commentService.getCommentCounts($scope.objectId, $scope.objectTypeId)
.then(function (result) { $scope.commentCount = result; });
};
function initialize() {
commentService.getInitData($scope.objectId, $scope.objectTypeId)
.then(function (result) {
$scope.commentCount = result.commentCount;
$scope.resourceStrings = result.resourceStrings;
});
}
}]);
angular.module('comment-widget').directive('commentWidget', function () {
var template =
'<div>' +
'<button type="button" class="buttonL">{{resourceStrings.commentButton}}</button><button type="button" class="buttonR">{{commentCount}}</button>' +
'</div>';
return {
restrict: 'E',
replace: true,
scope: {
objectId: '=',
objectTypeId: '='
},
controller: 'commentCtrl',
template: template
}
});
<script>
$(function () {
$('#refresh-button').click(function() {
$('#my-widget').trigger('comment.refresh');
alert('comments were refreshed');
});
})
</script>
link: function (scope, element, attrs) {
element.on('comment.refresh', function () {
scope.refreshComments();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment