簡體   English   中英

Angular JS,從指令中的控制器更新$ scope

[英]Angular JS, update $scope from controller in directive

我有以下情況:

在我的應用我有一個測驗,我存儲得分和當前問題為$scope.current$scope.scoreMainCtrl ,然后我有一個指令稱為問題,我展示的問題,並像選擇:

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'
        };
    });

在我的html中,我具有以下結構:

<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>

我的問題是,如何從指令鏈接函數更新$scope.score$scope.current

有人可以最好的方式向我解釋嗎?

在您有指令並想要更新父控制器作用域的情況下,我認為最好將模型與點一起使用.

為此,您需要在父控制器中稍微更改模型

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

然后在指令中你可以做

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

如果您引用類似quiz.score的模型,則它不會在當前范圍內創建score ,而是會找到父模型quiz並更改score

希望有道理

暫無
暫無

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

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