Angular JS,在指令中从控制器中更新$scope

Angular JS, update $scope from controller in directive

本文关键字:控制器 更新 scope Angular 指令 JS      更新时间:2023-09-26

我有以下情况:

在我的应用程序中,我有一个测验,我将分数和当前问题存储为$scope.current, $scope.scoreMainCtrl中,然后我有一个名为question的指令,在那里我显示问题和选择,如:

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

希望你能理解