如何将参数从AngularJS指令传递给AngularJS控制器函数

时间:2018-06-21 19:08:50

标签: angularjs angularjs-directive isolate-scope

预先感谢,实际上我想从app.Directive调用控制器中的一个函数,请任何人让我知道如何调用?还我将参数传递给该函数吗?我是angular的新手,这是所有代码

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 个答案:

答案 0 :(得分:3)

在隔离范围的情况下,指令范围完全不知道其父范围。

要调用控制器的函数,您必须将该函数绑定到指令的作用域,然后从指令内部调用作用域函数。

例如:

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>

供参考-https://plnkr.co/edit/fMIsQ87jgdx49QSnWq4o?p=preview