Dee J. Dee J. - 4 months ago 21
AngularJS Question

How to call a function inside a controller in a directive on ng-click

I have the following directive designed to call a modal dialog on button click:

.directive('transWizardModal', function () {
return {
restrict: 'E',
scope: { show : '='},
replace:true,
transclude: true,
controller: function($scope, $filter,spService, spHelper, itemContainer) {
$scope.toggleModal = function() {
$scope.convertArray();

$scope.modalShown = !$scope.modalShown;
$scope.currentQuestionIndex = 0; // initialize question index
$scope.answerCollection = []; // initialize collection
$scope.answerCollection .value = null;
$scope.choicesSelected = ""; // initialize for validation

$scope.currentQuestionObject = $scope.wizardQuestionSet[0]; // start from question #1
};

// lots more functions here...
},
link: function(scope, element, attrs) {
scope.dialogStyle = {};

if (attrs.width) {
scope.dialogStyle.width = "640px";
}

if (attrs.height) {
scope.dialogStyle.height = "660px";
}

scope.hideModal = function () {
scope.show = false;
};

},
template:'<div class=\"ng-modal\" ng-show=\'show\'>' +
'<div class=\"ngdialog-overlay\" ng-click=\'hideModal()\'></div>' +
'<div class=\"ng-modal-dialog\" ng-style=\'dialogStyle\'>' +
'<div class=\"ng-modal-close\" ng-click=\'hideModal()\'>X</div>' +
'<div class=\"ng-modal-dialog-content\" ng-transclude></div>' +
'</div>' +
'</div>'
};


And in my HTML, I have the following button designed to call toggleModal() on ng-click:

<div class="expandStory" style="float:left;padding-right:10px;">
<span ng-click="$scope.toggleModal()" class="carousel-btns">
Call my Modal
</span>
</div>


I've tried calling toggleModal() using this approach to no avail. Am I missing something here?

Any help would be appreciated.

Thank you as always for the tips. :)

EDIT: @developer033, I'm calling the directive in my HTML like this:

<trans-wizard-modal show="carousel.modalShown" width="750px" height="auto">
<!-- do something -->
</trans-wizard-modal>

Answer

When using ng-click, don't use $scope

instead of ng-click="$scope.toggleModal() Try this ng-click="toggleModal()

this fiddle shows ng-click, onclick, and click event listener methods

hope this helps :)