2

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);
            }
        };
 }
}});
georgeawg
  • 48,608
  • 13
  • 72
  • 95
Frank
  • 41
  • 5

1 Answers1

3

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

georgeawg
  • 48,608
  • 13
  • 72
  • 95
amrender singh
  • 7,949
  • 3
  • 22
  • 28
  • Thank you very much, I got this solution,Really I was stuck from two days on this issue.It perfectly working for me. – Frank Jun 21 '18 at 21:31
  • For more information on expression binding with `&`, see [AngularJS Comprehensive API Reference - scope](https://docs.angularjs.org/api/ng/service/$compile#-scope-). – georgeawg Jun 22 '18 at 01:04
  • @amrendersingh I did it, Thanks – Frank Jun 22 '18 at 07:21