简体   繁体   中英

Angular JS, update $scope from controller in directive

I have the following situation:

In my app I have a quiz, I store the score and the current question as $scope.current , $scope.score in MainCtrl , then I have a directive called question where I show the question and the choices like:

angular.module('quiz')
    .directive('myQuestion', function() {
        return {
            restrict: 'EA',
            replace: true,
            scope: {
                question: '=',
                index: '='           
            },

        link: function(scope) {



            scope.validate = function(index) {
                var isCorrect = index === scope.question.correct;

                if(isCorrect) {
                    console.log('Correct!');


                    //$scope.score += 10 ($scope score from MainCtrl)

                }

                if(!isCorrect) {
                    console.log('Incorrect!');

                    scope.correct = false;
                }

                //$scope.current += 1;

            };


            templateUrl: 'assets/javascript/tpl/question.html'
        };
    });

In my html I have the following structure:

<div class="quiz">

<h2>Current Question: {{current}}</h2>
<h2>Your score: {{score}}</h2>

<my-question ng-repeat="q in questions track by $index"
             ng-if="isCurrent($index)" //in controller i compare $index with $scope.current
             question="q"
             index="$index"></my-question>

</div>

My question is, how can I update $scope.score or $scope.current from the directive link function?

Can someone explain me please the best way?

In the case where you have directive and want to update parent controller scope I think it would be best to use model with a dot .

For that you need to change model a bit in parent controller

$scope.quiz = {
  score: 0
  current: 0
}

then in directive you can do

$scope.quiz.score = 'whatever, really'
$scope.quiz.current = 'current index'

if you refer to a model like that quiz.score then it will not create score on current scope but instead it will find parent model quiz and change the score

Hope that makes sense

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM