0

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?

1 Answer 1

1

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

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

1 Comment

Damn it, I completly forgot about the KISS principle

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.