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);
            }
        };
 }
}});
1
  • 1
    @LuizCarlos Thank you sir, I got the solution which is mention below. Commented Jun 21, 2018 at 21:34

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much, I got this solution,Really I was stuck from two days on this issue.It perfectly working for me.
For more information on expression binding with &, see AngularJS Comprehensive API Reference - scope.
@amrendersingh I did it, Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.