2

在此先感谢,实际上我想从 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);
            }
        };
 }
}});
4

1 回答 1

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

于 2018-06-21T19:51:32.877 回答