Thanks in advance,Actually I want to call a function in controller from app.Directive, Please anyone let me know How I can call?Also I passing parameter to that function?I'm new in angular and here is all code.
var app = angular.module('quizApp', []);
app.controller("SaveCtrl", function (scope) {
$scope.Save = function (score) {
$scope.TestDetailsViewModel = {};
$scope.TestDetailsViewModel.CorrectAnswer = $scope.score;
$http({
method: "post",
url: "/Home/ResultSave",
datatype: "json",
data: JSON.stringify($scope.TestDetailsViewModel)
}).then(function (response) {
alert(response.data);
})
};})
app.directive('quiz', function (quizFactory) {
return {
restrict: 'AE',
scope: {},
templateUrl: '/Home/Dashboard',
link: function (scope, elem, attrs) {
scope.getQuestion = function () {
var q = quizFactory.getQuestion(scope.id);
if (q) {
scope.question = q.question;
scope.options = q.options;
scope.answer = q.answer;
scope.answerMode = true;
} else {
scope.quizOver = true;
//Calling function save(); in Controller
//scope.Save(scope.score);
}
};
}
}});
In the case of an isolated scope, the directive scope is completely unaware of its parent’s scope.
To call a function of a controller you have to bind that function to the scope of directive and then call scope functions from inside the directive.
For example:
app.controller('MainCtrl', function($scope) {
$scope.commonFunc = function(passed){
$scope.name = passed;
};
});
app.directive('demodirective', function(){
return {
scope: {
commonFunc: '&'
},
link: function(scope){
scope.commonFunc({passed:"world"});
}
};
});
HTML
<body ng-controller="MainCtrl">
<demodirective common-func="commonFunc(passed)">
</demodirective>
Hello {{name}}
</body>
For Reference - https://plnkr.co/edit/fMIsQ87jgdx49QSnWq4o?p=preview