2015-10-19 100 views
0

我有以下的情況更新$範圍:角JS,從控制器指令

在我的應用我有一個測驗,我存儲得分和當前問題的$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

有人可以解釋我請最好的方法嗎?

回答

1

在這種情況下,你有指令,並要更新父控制器的範圍,我認爲這將是最好用的模型以點.

對於您需要更改模型父控制器有點

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

然後指示你可以做

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

,如果你是指像quiz.score一個模型,然後它不會產生score目前的範圍,而是它會找到父模型quiz和改變score

希望是有道理的

+0

靠,我完全地忘記了KISS原則 – Hiero