簡體   English   中英

如何將參數從AngularJS指令傳遞給AngularJS控制器函數

[英]How to Pass parameter from AngularJS Directive to AngularJS controller function

在此先感謝您,實際上我想從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);
            }
        };
 }
}});

在隔離范圍的情況下,指令范圍完全不知道其父級的范圍。

要調用控制器的函數,您必須將該函數綁定到指令的作用域,然后從指令內部調用作用域函數。

例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM